Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBoxFor helper mixes day and month in dates

Please, consider the following example:

  1. view model

    public class FooViewModel
    {
        public DateTime Date { get; set; }
    }
    
  2. controller

    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index(FooViewModel foo)
        {
            return View(foo);
        }
        [HttpPost]
        public ActionResult Submit(FooViewModel foo)
        {
            return RedirectToAction("Index", foo);
        }
    }
    
  3. 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" />
    }
    
  4. 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:

  1. after first submit
  2. after resubmit

What can I do to make it work properly?


Actually I tried to format the value of the editor:

  1. @Html.TextBoxFor(m => m.Date, new { value = Model.Date.ToString("dd.MM.yyyy") })
  2. using editor templates, as shown in MVC 2 Editor Template with DateTime, only of course adopted to MVC3; and I also used EditorFor helper instead to make the template be utilized.
  3. using 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...

like image 905
horgh Avatar asked Oct 22 '22 12:10

horgh


1 Answers

Please, try slightly changed version:
@Html.TextBoxFor(m => m.Date, new { @Value = Model.Date.ToString("dd.MM.yyyy") })

like image 87
Vladimir Avatar answered Oct 24 '22 04:10

Vladimir