您的位置:首页 > 其它

MVC中,提交后界面Model值未能更新的原因及优化。

2012-08-10 16:05 417 查看
假设有如下代码:

View/Time/index.cshtml



@model  MvcApplication1.Models.timeModel
<h2>Time</h2>
@using (Html.BeginForm("Index", "Time"))
{
<B>Get Current time:</B> @Html.TextBoxFor(m => m.currenttime)<br />
<B>Current time:</B> @Model.currenttime<br />
<p>
<input type="submit" value="search" />
</p>
}

TimeController.cs

public ActionResult Index()
{
MvcApplication1.Models.timeModel model = new Models.timeModel();
model.currenttime = DateTime.Now.TimeOfDay;
return View(model);
}

[HttpPost]
public ActionResult Index(MvcApplication1.Models.timeModel model)
{
model.currenttime = DateTime.Now.TimeOfDay;
return View(model);
}

结果如下:





点击submit之后





点击后发现,textboxfor中的值并没有改变,但是model的值其实已经改变了。

这是因为controller的ModelState属性,是dictionary类型,它包含了所有的要提交的值和验证的错误信息。在返回View的时候,文本框之类的值由ModelState所持有,因此没有得到更新,无法在界面上显示。最简单的做法就是使用ModelState.Clear(),或者ModelState.Remove("currenttime"); 之类的方法。但是也存在一些风险,比如把验证的错误信息也清除了。

先看一下效果。

public ActionResult Index()
{
MvcApplication1.Models.timeModel model = new Models.timeModel();
model.currenttime = DateTime.Now.TimeOfDay;
return View(model);
}

//每次post重新赋值时间给model
[HttpPost]
public ActionResult Index(MvcApplication1.Models.timeModel model)
{
ModelState.Remove("currenttime");
model.currenttime = DateTime.Now.TimeOfDay;
return View(model);
}





但是这种方法并不安全,因为如果是clear方法可能会清空ModelState中验证信息。而且刷新页面的时候,也会有重复提交的风险。





改成如下方式,把post方式转换成get方式,这样就避免了刷新时候会弹出重复提交的按钮。用TempData或者Session作为临时保存数据。

public ActionResult Index()
{
Models.timeModel model = new Models.timeModel();
if (TempData["timeModel"] != null)
{
model = TempData["timeModel"] as Models.timeModel;
}
else
{
model.currenttime = DateTime.Now.TimeOfDay;
}
return View(model);
}

//把post方式转换成get方式
[HttpPost]
public ActionResult Index(MvcApplication1.Models.timeModel model)
{
model.currenttime = DateTime.Now.TimeOfDay;
TempData["timeModel"] = model;
return RedirectToAction("Index");
}


本文出自 “一只博客” 博客,请务必保留此出处http://cnn237111.blog.51cto.com/2359144/960369
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: