I'm trying to figure out why my view is not restoring the data to its original state after my form has been submitted and I'm returning the relevant ViewModel and I'm setting the ModelState.AddModelError("", "error");
When my Edit page is requested, I call a method which builds my view model and passes it to my view and everything gets displayed as expected:
public ActionResult Edit(string id, string returnUrl)
{
if (ReferenceEquals(id, null))
return HttpNotFound();
var vm = GetOrganzationEditViewModel(id, returnUrl);
return View(vm);
}
When I make some changes to the fields available in my view and I submit it, I perform some server side validation and if it fails one of the specific condition, I requests the ViewModel as above by calling the same method i.e. GetOrganzationEditViewModel
using the same parameter as when the page was requested as these are included in the ViewModel and I'm also returning the relevant error using the ModelState.AddModelError
.
if ((organizationModelFromDb.MembershipType == MembershipType.Full)
{
ModelState.AddModelError("", $"Test Error:");
return View("Edit",GetOrganzationEditViewModel(organizationEditViewModel.
Organization.OrganizationId, organizationEditViewModel.ReturnUrl));
}
It does display the error as expected in my ValidationSummary
but I was under the impression that by returning the ViewModel, it would re-fill my values with the ViewModel's values returned, but it actually leaves the values as they were when I edited them.
My Razor page has fields that are binded to my ViewModel and it looks pretty standard:
<div class="form-group">
@Html.LabelFor(model => model.Organization.Website, htmlAttributes: new { @class =
"control-label col-md-3"})
<div class="col-md-5">
@Html.EditorFor(model => model.Organization.Website, new
{htmlAttributes = new { @class = "form-control", id = "txtWebsite" } })
@Html.ValidationMessageFor(model => model.Organization.Website, "", new { @class =
"text-danger" })
</div>
</div>
Am I missing something or am I suppose to handle this differently?
Thanks