将Partial View中的ValidationSummary返回给Ajax错误处理程序 - 没有其他任何东西得到渲染

时间:2014-02-19 15:50:45

标签: ajax asp.net-mvc-4

我正在调用一个来自Ajax的方法,它通过加载部分视图来更新页面中的某些内容。适当地设置一个包含的属性。

这一切都正常但我在使用ValidationSummary控件进行服务器端验证时遇到问题。我正在使用其他地方建议的方法将ValidationSummary粘贴在局部视图中。 (我实际上关闭了客户端验证&我正在尝试使用客户端验证使用的相同验证摘要来使服务器端验证工作)

当存在验证错误时,ajax错误处理程序应使用返回的部分视图更新div的内容。

所有这一切都可行,因为验证摘要是使用预期的错误消息呈现的,除了除了包含验证摘要及其包含元素的部分视图之外的其他内容没有显示的事实。即没有兄弟姐妹/ div被渲染

我真的不知道发生了什么。相反,如果我在错误处理程序中注释掉使用partial更新div的行,我会再次看到整个表单。

我正在使用ExceptionFilter:

public class ValidationErrorAttribute : FilterAttribute, IExceptionFilter
{
public virtual void OnException(ExceptionContext filterContext)
{
    if (filterContext == null)
    {
        throw new ArgumentNullException("filterContext");
    }

    if (filterContext.Exception != null)
    {
        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        filterContext.HttpContext.Response.StatusCode =  
        (int)System.Net.HttpStatusCode.BadRequest;
        //return the partial view containing the validationsummary and set the ViewData
        //so that it displays the validation error messages
        filterContext.Result = new PartialViewResult { ViewName = "validation",   
        ViewData = filterContext.Controller.ViewData  };
    }
}
}

当出现验证错误时,抛出一个validationexception 触发过滤器的OnException方法

    //Controller
    [HttpPost]
    [ValidationErrorAttribute]
    public ActionResult Save(ConsumptionData consumptionData)
    {
        if (ModelState.IsValid)
        {
            var dto = Mapper.Map<ConsumptionData, ConsumptionDataDto>(consumptionData);
            var refId = _personalProjectionRepository.AddPersonalProjectionRecord(dto);
            consumptionData.ReferenceId = refId;
            return PartialView("Reference", consumptionData);
        }
        else
        {
            throw new ValidationException();
        }   
    }

验证部分视图:

       @model PersonalProjection.Web.Models.ConsumptionData
       @Html.ValidationSummary()

和jquery:

        $('form').submit(function () {
        var form = $(this);
        if (form.valid())
        {

            $.ajax({
                url: form.attr("action"),
                type: "POST",
                dataType: "html",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({
                    SiteId: $('#siteid').val(),
                    ElectricityConsumption: $('#electricityconsumption').val(),
                    ElectricitySpend: $('#electricityspend').val(),
                    GasConsumption: $('#gasconsumption').val(),
                    GasSpend: $('#gasspend').val()
                }),
                success: function (result) {
                    $('#rightPanelSection').html(result);
                },
                error: function (jqXHR) {
                    $('#validationSummary').html(jqXHR.responseText);
                }

            });
        }
        return false;
    });

和index.cshtml标记

 <div class="panel panel-outcome">


 @using (Html.BeginForm("Save", "Home", FormMethod.Post, (object)new { ID  =  
 "projectionForm" }))

{
<div id="validationSummary"/>

<div id="topPanelSection" class="panel-section">
    @Html.LabelFor(m => m.SiteId, new { id = "siteidlabel" })
    @Html.TextBoxFor(m => m.SiteId, ViewBag.TextBoxDisabled ? (object)new { id = 
    "siteid", disabled = true, maxlength = 9, @class = "input-disabled", @Value = 
    ViewBag.SiteId } : new { id = "siteid", maxlength = 9 })
    <span id="errorText" class="error-text" />
</div>
<div id="leftPanelSection" class="panel-section">
    <div class="column-heading">
        <span class="column-heading-left">Total Cost</span>
        <span class="column-heading-right">Total Consumption</span>
    </div>
    <div class="panel-section-row"> 
        @Html.LabelFor(m => m.ElectricitySpend, new { id = "electricitylabel" })   
        <span>£</span>  
         @Html.TextBoxFor(m => m.ElectricitySpend, new { @class = "textbox-right-
         margin", id = "electricityspend" })  
         @Html.TextBoxFor(m => m.ElectricityConsumption, new { @class = "textbox-
         left-margin", id = "electricityconsumption" }) 
        <span>kWhs</span>
    </div> 
    <div class="panel-section-row">
        @Html.LabelFor(m => m.GasSpend, new { id = "gaslabel" })   
        <span>£</span>  
         @Html.TextBoxFor(m => m.GasSpend, new { @class = "textbox-right-margin", id = 
         "gasspend" })  
         @Html.TextBoxFor(m => m.GasConsumption, new { @class = "textbox-left-margin",
         id = "gasconsumption" }) 
        <span>kWhs</span>
    </div>
    <div class="panel-section-row">
        <button type="reset" id="resetbutton">Reset Form</button>
        <button type="submit">Generate Reference Id</button>
    </div>
</div>
<div id="rightPanelSection" class="panel-section">
    @Html.Partial("Reference", Model)
</div>

}

1 个答案:

答案 0 :(得分:0)

我对Ajax很新,所以这可能是一个小学生的错误,但这里有:

这是因为当我使用这个jquery时

$('#validationSummary').html(jqXHR.responseText);

更新此

<div id="validationSummary"/>

它不喜欢结束标签&amp;它搞砸了

更改为

    <div id="validationSummary">

    </div>

它运作正常。