2013-04-11 117 views
4

请考虑下面的例子:TextBoxFor帮手混入日期的日期和月份

  1. 视图模型

    public class FooViewModel 
    { 
        public DateTime Date { get; set; } 
    } 
    
  2. 控制器

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

    routes.MapRoute(
        null, 
        "", 
        new { controller = "Home", action = "Index" } 
    ); 
    routes.MapRoute(
        null, 
        "{action}", 
        new { controller = "Home" }, 
        new { action = "Submit" } 
    ); 
    

的问题是,表单提交日期编辑后得到的值与日和月交换:

  1. after first submit
  2. after resubmit

我能做些什么才能使其正常工作?


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

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

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


最后我(跟随the answer by 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"))); 
    } 

如果有一种方法可以实现同样的结果任何辅助方法仍然是一个秘密,我...

+0

如果格式化日期,该怎么办? – 2013-04-11 06:26:01

+0

@HanletEscaño我确实需要在编辑器中格式化日期,这确实也应该解决问题。然而,我没有格式化它...我会在一段时间内描述我在这个问题的尝试 – horgh 2013-04-11 06:31:39

+0

我猜数据库中的日期格式是不同的,这就是为什么它导致的问题,你可以将日期格式应用到您的ViewModel (如果你使用它们来绑定视图?) – dakait 2013-04-11 06:38:29

回答

3

请尝试些许变化版本:
@Html.TextBoxFor(m => m.Date, new { @Value = Model.Date.ToString("dd.MM.yyyy") })

+0

我绝对确定我在开始时用大写字母'V'和'@'试过了,它不起作用。我错了... – horgh 2013-04-11 07:57:12