MVC3,Razor视图,EditorFor,查询字符串值会覆盖模型值

时间:2011-09-24 19:23:32

标签: asp.net-mvc-3

我有一个采用DateTime的控制器动作?通过查询字符串作为post-redirect-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" />
}

我的问题有两个:

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

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

有什么想法吗?

1 个答案:

答案 0 :(得分: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);
}

我必须同意这种行为不是很直观,但它是设计的,所以人们应该真正习惯它。

以下是发生的事情:

  • 当您请求/ Home / Index时,ModelState内部没有任何内容,因此Html.EditorFor(x => x.Date)帮助程序使用您的视图模型的值(您已设置为DateTime.Now),当然它应用了正确的格式< / LI>
  • 当您请求/Home/Index?date=1/1/1时,Html.EditorFor(x => x.Date)帮助器检测到date内的ModelState变量等于1/1/1并且它完全使用此值忽略视图模型中存储的值(就DateTime值而言几乎相同,但当然不应用格式化)。
相关问题