在一系列页面视图中遇到视图状态问题 - 在Razor页面的初始视图中,我使用Html.HiddenFor如下:
@Html.HiddenFor(x => Model.err)
@Html.HiddenFor(x => Model.errField)
@Html.HiddenFor(x => Model.errMessage)
@Html.HiddenFor(x => Model.IsMove)
Run Code Online (Sandbox Code Playgroud)
这似乎工作正常.我的隐藏输入标记包含正确的值.但是,当我提交表单[HTTPPost]并在我的控制器操作中更新模型时...
model.err = transHelper.err;
model.errField = transHelper.errField;
model.errMessage = transHelper.errMessage;
return View(model);
Run Code Online (Sandbox Code Playgroud)
隐藏字段似乎不更新,它们包含初始视图中的原始值.但是当我在同一个剃刀视图中的另一个上下文中使用这些字段时,这样...
@*
this seems to not update correctly...
@Html.HiddenFor(x => Model.err)
@Html.HiddenFor(x => Model.errField)
@Html.HiddenFor(x => Model.errMessage)
@Html.HiddenFor(x => Model.IsMove)
*@
<input type="hidden" id="err" value="@Model.err" />
<input type="hidden" id="errField" value="@Model.errField" />
<input type="hidden" id="errMessage" value="@Model.errMessage" />
<input type="hidden" id="IsMove" value="@Model.IsMove" />
</div>
Run Code Online (Sandbox Code Playgroud)
然后输入字段正确更新.我甚至创建了一个View Helper来帮助调试,并且在所有情况下,模型似乎都有正确的数据 HtmlHelper<TModel>- 我甚至返回模型,return Json(model); …
该模型
class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器动作
[HttpPost]
public ActionResult GetAddress(Address model)
{
if (!String.IsNullOrEmpty(model.Zip))
{
model.City = GetCityByZip(model.Zip);
}
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
风景
<div class="formrow">
@Html.LabelFor(model => model.City)
@Html.TextBoxFor(model => model.City)
@Html.ValidationMessageFor(model => model.City)
</div>
<div class="formrow">
@Html.LabelFor(model => model.State)
@Html.DropDownListFor(model => model.State, (IEnumerable<SelectListItem>)ViewBag.States, new { style = "width:217px;" })
@Html.ValidationMessageFor(model => …Run Code Online (Sandbox Code Playgroud) 在MVC Form Post中使用隐藏字段时遇到问题.当通过HTML Helper生成隐藏字段时,它不会在回发期间保留它的值.但是当使用HTML标签时,它可以正常工作.
不幸的是,这个人花了我一整天的时间来完成这项工作.
这是我正在做的...(原谅任何拼写,重新输入的代码为SO):
查看模型
public class SomeViewModel
{
public int MyProperty1 { get; set; }
public int MyProperty2 { get; set; }
public int MyProperty3 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
发布方法
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyActionMethod(SomeViewModel someViewModel, string command)
{
...
...
// someViewModel.MyProperty1
...
...
}
Run Code Online (Sandbox Code Playgroud)
视图
@using (Html.BeginForm("MyActionMethod", "SomeController", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.MyProperty1)
<div class="col-md-2">
<input type="hidden" value=@Model.MyProperty1 name="MyProperty1" />
<input type="submit" name="command" value="Button1" …Run Code Online (Sandbox Code Playgroud)