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”(计划将验证日期,如果查询字符串无效,则默认它)。
任何想法?
啊 - 真棒的答案,非常感谢:-) – magritte