2

目前我有这样的剃刀View

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()

报告控制器.cs

public PartialViewResult TotalPaymentsByMonthYear(MyViewModel model,
       string reportName)
{
    if (!ModelState.IsValid)
    {
        return PartialView("ValidationSummary", model);
    }

    model.ReportName = reportName;

    return PartialView("Chart", model);
}

我想做的是:PartialView我不是在 this 中显示验证错误,而是在寻找一种将此验证错误消息发送到我在_Layout.cshtml文件中定义的 DIV 元素的方法。

_Layout.cshtml

<div id="message">

</div>

@RenderBody()

我想异步填充这个 DIV 的内容。这可能吗?我怎样才能做到这一点?

4

1 回答 1

4

就个人而言,我会扔掉Ajax.*助手并这样做:

@model MyApp.Web.ViewModels.MyViewModel

<div id="message"></div>

@using (Html.BeginForm("TotalPaymentsByMonthYear", new { reportName = "CreateTotalPaymentsByMonthYearChart" }))
{
    ...
}

<div id="chartimage">
    @Html.Partial("ValidationSummary")
</div>

然后我会使用自定义 HTTP 响应标头来指示发生了错误:

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 标头存在的成功回调中,我将部分或部分注入结果:

$('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;
});
于 2011-05-18T07:00:25.990 回答