How do I update the DIV in _Layout.cshtml with a message after the Ajax form is submitted?
I currently have Razor View
like this:
TotalPaymentsByMonthYear.cshtml
@model MyApp.Web.ViewModels.MyViewModel
@using (@Ajax.BeginForm("TotalPaymentsByMonthYear",
new { reportName = "CreateTotalPaymentsByMonthYearChart" },
new AjaxOptions { UpdateTargetId = "chartimage"}))
{
<div class="report">
// MyViewModel fields and validation messages...
<input type="submit" value="Generate" />
</div>
}
<div id="chartimage">
@Html.Partial("ValidationSummary")
</div>
Then I show PartialView
which has @Html.ValidationSummary()
in case of validation errors.
ReportController.cs
public PartialViewResult TotalPaymentsByMonthYear(MyViewModel model,
string reportName)
{
if (!ModelState.IsValid)
{
return PartialView("ValidationSummary", model);
}
model.ReportName = reportName;
return PartialView("Chart", model);
}
I would like to do this: instead of displaying validation errors in this PartialView
, I'm looking for a way to send this validation error message to a DIV element that I have defined in a file _Layout.cshtml
.
_Layout.cshtml
<div id="message">
</div>
@RenderBody()
I would like to fill the content of this DIV asynchronously. Is it possible? How can i do this?
a source to share
Personally, I would pick helpers Ajax.*
and do it like this:
@model MyApp.Web.ViewModels.MyViewModel
<div id="message"></div>
@using (Html.BeginForm("TotalPaymentsByMonthYear", new { reportName = "CreateTotalPaymentsByMonthYearChart" }))
{
...
}
<div id="chartimage">
@Html.Partial("ValidationSummary")
</div>
Then I would use a custom HTTP response header to indicate that an error has occurred:
public ActionResult TotalPaymentsByMonthYear(
MyViewModel model,
string reportName
)
{
if (!ModelState.IsValid)
{
Response.AppendHeader("error", "true");
return PartialView("ValidationSummary", model);
}
model.ReportName = reportName;
return PartialView("Chart", model);
}
and finally in a separate javascript file I would unobtrusively AJAXify this form and in the success callback based on the presence of this custom HTTP header I would enter the result in some part:
$('form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result, textStatus, jqXHR) {
var error = jqXHR.getResponseHeader('error');
if (error != null) {
$('#message').html(result);
} else {
$('#chartimage').html(result);
}
}
});
return false;
});
a source to share