TextBoxFor 助手在日期中混合日和月

hor*_*rgh 5 c# asp.net-mvc-3

请考虑以下示例:

  1. 视图模型

    public class FooViewModel
    {
        public DateTime Date { get; set; }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 控制器

    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index(FooViewModel foo)
        {
            return View(foo);
        }
        [HttpPost]
        public ActionResult Submit(FooViewModel foo)
        {
            return RedirectToAction("Index", foo);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 看法

    @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" />
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 路线

    routes.MapRoute(
        null,
        "",
        new { controller = "Home", action = "Index" }
    );
    routes.MapRoute(
        null,
        "{action}",
        new { controller = "Home" },
        new { action = "Submit" }
    );
    
    Run Code Online (Sandbox Code Playgroud)

问题是表单提交后,日期编辑器获取日期和月份切换的值:

  1. 第一次提交后
  2. 重新提交后

我该怎么做才能使其正常工作?


其实我试图格式化编辑器的值:

  1. @Html.TextBoxFor(m => m.Date, new { value = Model.Date.ToString("dd.MM.yyyy") })
  2. 使用编辑器模板,如MVC 2 Editor Template with DateTime 所示,当然仅适用于 MVC3;而且我还使用了EditorForhelper 来使模板得到利用。
  3. 使用DataAnnotations[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMM/dd/yyyy}")]

这些都没有改变任何东西。编辑器的值既没有改变,也没有格式化。


最后,我(按照DrJokepu的回答)设法仅使用原始 HTML 完成这项工作,即没有帮助方法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")));
    }
Run Code Online (Sandbox Code Playgroud)

如果有一种方法可以使用任何辅助方法实现相同的结果,这对我来说仍然是一个秘密......