渲染使用隐藏的表单字段@ Html.HiddenFor [英] Rendering hidden form field using @Html.HiddenFor
问题描述
public class SearchForm {
//Note: Property is nullable
public DateTime? CurrentViewDate {get;set;}
public DateTime StartDate {get;set;}
}
//In the controller
//[GET]
public ActionResult Index()
{
}
//[POST]
public ActionResult Index(SearchForm formModel)
{
if(formModel.CurrentViewDate == null)
formModel.CurrentViewDate = DateTime.Now.AddDays(1d);
else
formModel.CurrentViewDate = formModel.CurrentViewDate.AddDays(1d);
formModel.StartDate = DateTime.Now;
}
//In view
@Html.HiddenFor(c => c.CurrentViewDate).
<input id="SearchForm_CurrentViewDate" name="SearchForm.CurrentViewDate"
type="hidden" value="5/25/2012 11:59:59 PM" />
<input type="submit" name="btnNext" id="btnNext" value="Go Increment" />
但是,当我点击提交值也被增加,但隐藏字段保存previous价值的唯一方式,它显示正确的值
如果做到这一点@ Html.HiddenFor(C => c.CurrentViewDate.Value),但随后在
重新发布该formModel.CurrentViewDate具有null值,因为绑定名称是不同的。
But, I when click submit the value does gets incremented but the hidden for field holds the previous value and the only way it displays correct value is If do this @Html.HiddenFor(c => c.CurrentViewDate.Value) , but then on the re-post the formModel.CurrentViewDate has null value since the binding names are different.
任何想法?这感觉就像它将从起始日期属性的日期时间值,而不是CurrentViewDate财产
Any ideas? It feels like it fetches the date time value from StartDate property instead of CurrentViewDate property
推荐答案
您需要,如果你打算修改它从ModelState中删除值:
You need to remove the value from the ModelState if you intend to modify it:
public ActionResult Index(SearchForm formModel)
{
ModelState.Remove("CurrentViewDate");
if(formModel.CurrentViewDate == null)
{
formModel.CurrentViewDate = DateTime.Now.AddDays(1d);
}
else
{
formModel.CurrentViewDate = formModel.CurrentViewDate.AddDays(1d);
}
return View(model);
}
您需要做的原因是因为所有的HTML佣工如TextBoxFor,HiddenFor,CheckBoxFor,......在ModelState中先看看他们的结合时,值之后,他们在模型中的样子。此行为是设计使然。如此以来,在POST操作有已经在ModelState中(即与请求一起发送的)的值就是这个值的被使用。
The reason you need to do this is because all Html helpers such as TextBoxFor, HiddenFor, CheckBoxFor, ... first look in the ModelState when binding their values and after that they look in the model. This behavior is by design. So since in your POST action there's already a value in the ModelState (the one that was sent with the request) it is this value that's being used.
每当你尝试修改一个POST控制器动作里面您的视图模型的一些特性,并期望这种变化的值以反映不要忘了ModelState中。
Everytime you attempt to modify some property on your view model inside a POST controller action and expect this change to reflect in the value don't forget about the ModelState.
这篇关于渲染使用隐藏的表单字段@ Html.HiddenFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!