I have the following Action in my controller:
[HttpPost]
public JsonResult RedirectToAspReportViewer(MvcReportPeriodSelectionViewModel periodFilter, MvcMultipleLocationSelectionViewModel locationFilter)
{
var jsonObject = new { HasErrors = false, strUrl = "/ASPReports/TreatmentOutcome.aspx" };
if (ModelState.IsValid)
{
try
{
//some code
}
catch (ValidationException ex)
{
this.HandleValidationErrors(ex);
jsonObject = new { HasErrors = true, strUrl = "/TreatmentOutcomeReport/Report/" };
}
}
return Json(jsonObject);
}
Then, in my Javascript, I have the following function, which get's called on my ajax post's OnSuccess function.
onSuccessCall: function (response) {
if (response.HasErrors === true) {
//window.location = window.location.href;
location.reload();
} else {
window.open(response.strUrl);
}
};
As you can see from above, if my reponse object has errors, I would like to stay on the current page, just refresh it so that my ModelState errors would still show.
The problem I am facing, is that when I call location.reload
, my ModelState errors do not show on my page. I have a feeling it is because I am posting to the server again, and the ModelState gets cleared.
How can I avoid this?
UPDATE I cannot just add the validation error to the JsonResult, and in the client side, update the necessary DOM to display the errors. On all of my views, I have the following shared view which returns my errors: Below is the sample:
@model ModelStateDictionary
@{
var cls = "alert-danger";
var type = ViewBag.Type;
if (type != null && type.ToString().ToLower() == "warning")
{
cls = "alert-warning";
}
var message = "Please attend to the following problems:";
if (ViewBag.Message != null && ViewBag.Message.ToString().Trim() != "")
{
message = ViewBag.Message.ToString().Trim();
}
}
@if (ViewData.ModelState.Keys.Any(k => ViewData.ModelState[k].Errors.Count() > 0))
{
<div class="alert @cls">
<button class="close" data-dismiss="alert" aria-hidden="true">× </button>
@Html.ValidationSummary(false, message)
</div>
}
This will get called at the top of all my views as follow:
<div id="valSummary">
@Html.Partial("_ValidationSummaryDisplay", ViewData.ModelState)
</div>