Antoine Pelletier Antoine Pelletier - 3 days ago 6
C# Question

Setting a format to a date retrieved by entity in MVC

Considering my model contains only :

public class TheModel
{
public SQL_Table TableInModel { get; set; }
}


SQL_Table
is a table retrieved with Entity Framework (I use SQL Server and EF).

I can retrieve the table object in the controller using :

[HttpPost]
public ActionResult ControllerName(TheModel mod)
{
mod.TableInModel = db.SQL_Table.First();
return View(mod);
}


Now binding that date correctly in a view... I tried :

@Html.TextBoxFor(t => t.TableInModel.Date, "{0:dd-MM-yyyy}" )


Which format the date correctly, but the value in the textbox is lost on postback and cannot be retrieved in the controller.

So I tried this instead :

@Html.EditorFor(t => t.TableInModel.Date)


This correctly send the date value to my controller on postback, but no format is applied on the textBox that is generated.

What is the way to format a date in this context while being sure the value isn't lost on postback ?

(when I try this in my controller
mod.TableInModel.Date
Date is null)

This is my web output :

My web output

Answer

Just make another property for everything that dosen't post back correctly and assign it into your controller, it's not worth trying to format AND retreive a property created by entity :

public class TheModel
{
    public SQL_Table TableInModel { get; set; }

    public DateTime Date {get;set;} // <- apply your format HERE
}

[HttpPost]
public ActionResult ControllerName(TheModel mod)
{
    mod.TableInModel = db.SQL_Table.First();
    mod.Date = mod.TableInModel.Date; 
}
Comments