2011-09-24 51 views
4

我有一个需要DateTime的控制器操作?通过查询字符串作为post-redirect-get的一部分。控制器看起来像例如MVC3,Razor视图,EditorFor,查询字符串值覆盖模型值

public class HomeController : Controller 
{ 
    [HttpGet] 
    public ActionResult Index(DateTime? date) 
    { 
     IndexModel model = new IndexModel(); 

     if (date.HasValue) 
     { 
      model.Date = (DateTime)date; 
     } 
     else 
     { 
      model.Date = DateTime.Now; 
     } 

     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(IndexModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      return RedirectToAction("Index", new { date = model.Date.ToString("yyyy-MM-dd hh:mm:ss") }); 
     } 
     else 
     { 
      return View(model); 
     } 
    } 
} 

我的模型是:

public class IndexModel 
{ 
    [DataType(DataType.Date)] 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")] 
    public DateTime Date { get; set; } 
} 

而剃刀的看法是:

@model Mvc3Playground.Models.Home.IndexModel 

@using (Html.BeginForm()) { 
    @Html.EditorFor(m => m.Date); 
    <input type="submit" /> 
} 

我的问题是双重的:

(1)日期格式施加在如果查询字符串包含日期值,则使用[DisplayFormat]属性的模型不起作用。 (2)模型中保存的值似乎被查询字符串值包含的值覆盖。例如。如果我在Index GET操作方法中设置了一个断点,并且手动设置日期等于今天说,如果查询字符串包含例如?date = 1/1/1,则在文本框中显示“1/1/1”(计划将验证日期,如果查询字符串无效,则默认它)。

任何想法?

回答

14

HTML辅助结合,所以当第一次使用的ModelState如果你打算修改一些值,它是存在于控制器动作内部模型的状态确保您从ModelState中首先除去它:

[HttpGet] 
public ActionResult Index(DateTime? date) 
{ 
    IndexModel model = new IndexModel(); 

    if (date.HasValue) 
    { 
     // Remove the date variable present in the modelstate which has a wrong format 
     // and which will be used by the html helpers such as TextBoxFor 
     ModelState.Remove("date"); 
     model.Date = (DateTime)date; 
    } 
    else 
    { 
     model.Date = DateTime.Now; 
    } 

    return View(model); 
} 

我必须同意这种行为不是很直观,但它是通过设计让人们真正适应它。

这里发生了什么:

  • 当你请求/首页/索引里面什么也没有的ModelState所以Html.EditorFor(x => x.Date)助手使用您的视图模型(您已设置为DateTime.Now)的价值,当然它适用正确的格式
  • 当你请求/Home/Index?date=1/1/1,该Html.EditorFor(x => x.Date)帮助检测到有内部ModelState等于1/1/1一个date变量,并使用这个值,完全无视存储您的视图模型中(这是相当多的条款Ø相同的值f日期时间值,但当然不应用格式)。
+0

啊 - 真棒的答案,非常感谢:-) – magritte

相关问题