Asp.net mvc 3 MVC3、Razor视图、EditorFor、查询字符串值覆盖模型值

Asp.net mvc 3 MVC3、Razor视图、EditorFor、查询字符串值覆盖模型值,asp.net-mvc-3,Asp.net Mvc 3,我有一个控制器动作需要一个日期时间?作为post重定向get的一部分,通过查询字符串。控制器看起来像 public class HomeController : Controller { [HttpGet] public ActionResult Index(DateTime? date) { IndexModel model = new IndexModel(); if (date.HasValue) {

我有一个控制器动作需要一个日期时间?作为post重定向get的一部分,通过查询字符串。控制器看起来像

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; }
}
而Razor的观点是:

@model Mvc3Playground.Models.Home.IndexModel

@using (Html.BeginForm()) {
    @Html.EditorFor(m => m.Date);
    <input type="submit" />
}
@model mvc3.Models.Home.IndexModel
@使用(Html.BeginForm()){
@EditorFor(m=>m.Date);
}
我的问题有两个:

(1) 如果查询字符串包含日期值,则使用[DisplayFormat]属性在模型上应用的日期格式无效

(2) 模型中保存的值似乎被查询字符串值包含的任何内容覆盖。例如,如果我在我的Index GET action方法中设置了一个断点,并手动将日期设置为今天,例如,如果查询字符串包含例如?date=1/1/1,则文本框中会显示“1/1/1”(计划是验证日期,如果查询字符串1无效,则默认为日期)


有什么想法吗?

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);
}
我必须同意这种行为不是很直观,但它是经过设计的,所以人们应该真正习惯它

下面是发生的情况:

  • 当您请求/Home/Index时,ModelState中没有任何内容,因此
    Html.EditorFor(x=>x.Date)
    helper使用视图模型的值(您已将其设置为
    DateTime.Now
    ),当然它会应用正确的格式
  • 当您请求
    /Home/Index?date=1/1/1
    时,
    Html.EditorFor(x=>x.date)
    帮助程序检测到
    ModelState
    中有一个
    date
    变量等于
    1/1/1
    ,并使用该值,完全忽略视图模型中存储的值(就DateTime值而言,这几乎是相同的,但当然没有应用任何格式)