Hello I am not able to retain values on multiple posts and “Post1” action function in my in my controller always has MyViewModelObj.Field2 as null .I expect it to retain the old value in the 2nd post How to I make the MyViewModel model class object persist the values ?
Mymodels.cs ( Model)
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 ( View )
@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 ( Controller )
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);
}
}
}