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

假设有如下代码:

View/Time/index.cshtml

 
 
  1. @model  MvcApplication1.Models.timeModel 
  2. <h2>Time</h2> 
  3. @using (Html.BeginForm("Index", "Time")) 
  4. {   
  5.    <B>Get Current time:</B> @Html.TextBoxFor(m => m.currenttime)<br /> 
  6.    <B>Current time:</B> @Model.currenttime<br /> 
  7.    <p>   
  8.    <input type="submit" value="search" />   
  9.    </p>   

TimeController.cs

        

 
 
  1. public ActionResult Index() 
  2.         { 
  3.             MvcApplication1.Models.timeModel model = new Models.timeModel(); 
  4.             model.currenttime = DateTime.Now.TimeOfDay; 
  5.             return View(model); 
  6.         } 
  7.  
  8.         [HttpPost] 
  9.         public ActionResult Index(MvcApplication1.Models.timeModel model) 
  10.         { 
  11.             model.currenttime = DateTime.Now.TimeOfDay; 
  12.             return View(model); 
  13.         } 

结果如下:

72DC65255D59474CA2709953F5E185D4

点击submit之后

52A359B2E01041FFBCCCC22D5DFF49D9

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

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

先看一下效果。

 
 
  1. public ActionResult Index() 
  2.     MvcApplication1.Models.timeModel model = new Models.timeModel(); 
  3.     model.currenttime = DateTime.Now.TimeOfDay; 
  4.     return View(model); 
  5.  
  6. //每次post重新赋值时间给model 
  7. [HttpPost] 
  8. public ActionResult Index(MvcApplication1.Models.timeModel model) 
  9.     ModelState.Remove("currenttime"); 
  10.     model.currenttime = DateTime.Now.TimeOfDay; 
  11.     return View(model); 

E2A5B8F73AF742DABDD2F25C6DCB75BC

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

08D99B427978423A8BC916A4CCC5E6A5

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

 

 
 
  1. public ActionResult Index() 
  2.        { 
  3.            Models.timeModel model = new Models.timeModel(); 
  4.            if (TempData["timeModel"] != null
  5.            { 
  6.                model = TempData["timeModel"as Models.timeModel; 
  7.            } 
  8.            else 
  9.            { 
  10.                model.currenttime = DateTime.Now.TimeOfDay; 
  11.            } 
  12.            return View(model); 
  13.        } 
  14.  
  15.  
  16.        //把post方式转换成get方式 
  17.        [HttpPost] 
  18.        public ActionResult Index(MvcApplication1.Models.timeModel model) 
  19.        { 
  20.            model.currenttime = DateTime.Now.TimeOfDay; 
  21.            TempData["timeModel"] = model; 
  22.            return RedirectToAction("Index"); 
  23.        } 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值