Please, consider the following example:
view model
public class FooViewModel
{
public DateTime Date { get; set; }
}
controller
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index(FooViewModel foo)
{
return View(foo);
}
[HttpPost]
public ActionResult Submit(FooViewModel foo)
{
return RedirectToAction("Index", foo);
}
}
view
@model MvcApplication1.Models.FooViewModel
<h1>@Model.Date</h1>
@using (Html.BeginForm("Submit", "Home", FormMethod.Post))
{
@Html.TextBoxFor(m => m.Date)
<input type="submit" value"Submit" />
}
routes
routes.MapRoute(
null,
"",
new { controller = "Home", action = "Index" }
);
routes.MapRoute(
null,
"{action}",
new { controller = "Home" },
new { action = "Submit" }
);
The problem is that after form submit the date editor gets values with day and month switched:
What can I do to make it work properly?
Actually I tried to format the value of the editor:
@Html.TextBoxFor(m => m.Date, new { value = Model.Date.ToString("dd.MM.yyyy") })
EditorFor
helper instead to make the template be utilized.DataAnnotations
: [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMM/dd/yyyy}")]
None of these changed anything. Neither the value of the editor changed, nor it appeared formatted.
In the end I (followed the answer by DrJokepu) managed to make this work only with raw HTML, i.e. no helper methods for DateTime
:
public static MvcHtmlString GetDateEditor(this FooViewModel model)
{
string temp = "<input id=\"Date\" type=\"text\" value=\"{0}\" name=\"Date\"
data-val-required=\"Please, enter a valid date\"
data-val=\"true\" />";
return MvcHtmlString.Create(
string.Format(temp,
model == null
? string.Empty
: model.Date.ToString("dd.MM.yyyy")));
}
If there is a way to achieve the same result with any of the helper methods remains a secret to me...
Please, try slightly changed version:@Html.TextBoxFor(m => m.Date, new { @Value = Model.Date.ToString("dd.MM.yyyy") })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With