目前我有一个剃刀查看
是这样的:
Currently I have a 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>
我然后显示一个 PartialView
具有 @ Html.ValidationSummary()
的情况下验证错误。
I then display a PartialView
that has a @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);
}
我想要做的是:不是在此显示验证错误 PartialView
,我在寻找发送此验证错误信息到DIV的方法我已经在 _Layout.cshtml
文件中定义的元素。
What I'd like to do is: instead of displaying validation errors within this PartialView
, I'm looking for a way of sending this validation error message to a DIV element that I have defined within the _Layout.cshtml
file.
_Layout.cshtml
<div id="message">
</div>
@RenderBody()
我想填的内容该div异步。这可能吗?我该怎么办呢?
I'd like to fill the content of this DIV asynchronously. Is this possible? How can I do that?
我个人会抛出阿贾克斯*
助手的路程,像这样做:
Personally I would throw Ajax.*
helpers away 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>
然后,我会使用自定义的HTTP响应头,以表明发生了错误:
Then I would use a custom HTTP response header to indicate that an error 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);
}
终于在一个单独的JavaScript文件,我会悄悄地AJAXify这种形式,并在此基础上定义HTTP标头的presence成功的回调我会在一个部分或其他注入的结果:
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 inject the result in one part or another:
$('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;
});