你好,我不能保留多個帖子的值,我在我的控制器中的「Post1」動作函數總是將MyViewModelObj.Field2設爲null。我期望它在第二個帖子中保留舊值 如何使MyViewModel模型類對象保持值?在多個帖子之間保留值
Mymodels.cs(型號)
namespace RetainTest.Models
{
public class MyViewModel
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public string Field4 { get; set; }
}
}
RetainView.cshtml(查看)
@model RetainTest.Models.MyViewModel
@{
ViewBag.Title = "RetainView";
}
<h2>RetainView</h2>
@using (Html.BeginForm("Post1", "Retain", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Field1);
@Html.HiddenFor(model => model.Field2);
@Html.HiddenFor(model => model.Field3);
@Html.HiddenFor(model => model.Field4);
<div class="form-horizontal">
<h4>MyViewModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Field1, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Field1, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Field1, "", new { @class = "text-danger" })
</div>
</div>
@{
if ( Model.Field2 == "Val2")
{
<div class="form-group">
@Html.LabelFor(model => model.Field2, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Field2, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Field2, "", new { @class = "text-danger" })
</div>
</div>
}
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
RetainController.cs(控制器)
namespace RetainTest.Models
{
public class RetainController : Controller
{
// GET: Retain
public ActionResult Index()
{
MyViewModel MyViewModelObj = new MyViewModel();
MyViewModelObj.Field1 = "Val1";
return View("RetainView", MyViewModelObj);
}
[HttpPost]
public ActionResult Post1(MyViewModel MyViewModelObj)
{
if (string.IsNullOrEmpty(MyViewModelObj.Field2))
{
MyViewModelObj.Field2 = "Val2";
}
return View("RetainView", MyViewModelObj);
}
}
}
您的視圖對於您的模型的每個屬性都有一個隱藏的輸入。 'DefaultModelBinder'爲請求中的每個屬性讀取第一個名稱/值對,並忽略所有其他屬性。由於隱藏的輸入是第一個,所以'EditorFor()'方法的值將被忽略。你只能綁定模型的初始值,而不是編輯的值(使得你的表單毫無意義)。刪除隱藏的輸入! –
和'MyViewModelObj.Field2 =「Val2」;'什麼都不做(參考[這個答案]的第二部分(http://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-值更新的代碼/ 26664111#26664111)的解釋)。如果你想用不同的值顯示一個視圖,那麼按照PRG模式(或者使用'ModelState.Clear();') –
謝謝@StephenMuecke,刪除這三個語句修復了它。 @ Html.HiddenFor(model => model.Field1); @ Html.HiddenFor(model => model.Field2); @ Html.HiddenFor(model => model.Field3); @ Html.HiddenFor(model => model.Field4); 我雖然隱藏的價值是一個職位,我意識到它永遠保留它 – AnnaDaKhokha