Asp.net 从MVC中的控制器返回JSON中的部分视图 我的处境

Asp.net 从MVC中的控制器返回JSON中的部分视图 我的处境,asp.net,asp.net-mvc,ajax,json,Asp.net,Asp.net Mvc,Ajax,Json,我的主页上显示了一个项目列表(调查)。当我单击某个特定项目的编辑按钮时,我会弹出一个模式窗口,其中包含要编辑的项目详细信息。当用户单击保存时,我通过ajax提交表单。根据ModelState.IsValid==true,我希望使用验证信息更新模式,或者关闭模式并使用新信息更新项目列表 以下是我提交表格的方式: $('#editSurveyForm form').live('submit', function () { var f = $("#saveSurvey").pa

我的主页上显示了一个项目列表(调查)。当我单击某个特定项目的编辑按钮时,我会弹出一个模式窗口,其中包含要编辑的项目详细信息。当用户单击保存时,我通过ajax提交表单。根据ModelState.IsValid==true,我希望使用验证信息更新模式,或者关闭模式并使用新信息更新项目列表

以下是我提交表格的方式:

    $('#editSurveyForm form').live('submit', function () {
        var f = $("#saveSurvey").parents("form");
        var action = f.attr("action");
        var serializedForm = f.serialize();
        $.ajax({
            type: "POST",
            url: action,
            dataType: "html",
            data: serializedForm,
            success: function (result) {
                //TODO - I need an indicator that validation was successful

                //If Validation Failed reload form with validation errors
                $('#editSurveyModal').html(result);

                //If Successful, reload Survey Partial View
                //$('#surveyBox').html(result);
            }
        });
        return false;
    });
我的问题 我能想到的唯一一件事就是从我的控制器返回JSON,并带有一个标志,指示ModelState.IsValid的状态以及我应该显示的相应部分

1) 我该怎么做

2) 有更好的办法吗

更新 我发现:


但我似乎更可能是把整个事情搞错了。

您可以返回一个标志,告诉您是否有错误,并根据该标志,返回一组不同的数据。 如果是错误,则返回如下内容:

{success: false, errors: ['Name invalid','email invalid']}
如果它是正确的:

{success: true, Name:'new name',email: 'new email'}
你的剧本呢

....
$.ajax({
        type: "POST",
        url: action,
        dataType: "html",
        data: serializedForm,
        success: function (result) {
            if(!result.success)
            {
                  //Show errors     
            }
            else
            {
                  // Update data
            }
        }
    });
.....
要显示错误,可以在模式弹出窗口中添加一个div,然后针对result.errors上的每个项目,在error div中添加一个div

如果成功为true,则查找您单击的项目,并使用结果中的日期更新它


如果您不知道如何执行此操作,请告诉我。

跳过使用JSON的一种方法是在返回的HTML中查找某些元素。如果您正在使用任何html帮助程序处理验证消息(
html.ValidationSummary(),html.ValidationMessageFor()
),则这些帮助程序将使用您可以查找的特定类呈现元素以决定结果。如果没有,你可以制定自己的标准

例如,如果您使用的是
Html.ValidationSummary
-方法,它将呈现一个包含类
验证摘要错误的列表。因此,您可以像这样设置一个变量,然后相应地处理响应

var isValid = $(response).find(".validation-summary-errors").length == 0;
所以在你的情况下:

success: function (result) {
    var isValid = $(result).find(".validation-summary-errors").length == 0;

    //If Successful, reload Survey Partial View
    if (isValid) {
         $('#surveyBox').html(result);
    }
    //If Validation Failed reload form with validation errors
    else {
        $('#editSurveyModal').html(result);
    }
}
    <div class="container container-Top">
        <h4>Lista de categorias produtos</h4>
        <p>
            <hr />
            <br />
            @using (Html.BeginForm())
            {
                <div class="form-group">
                    <div class="col-lg-4">
                        @Html.TextBox("NomeCategoria", null, new { @class = "form-control" })
                    </div>
                    @Html.ActionLink("Pesquisar", null, null, new { @class = "btn btn-default", @id = "Pesquisar" })
                </div>
            }                       
            <br />
            <br />
            <br />
            <div id="DvDetalheCategoria" class="form-group">
                @Html.Partial("_DetalhesCategoria", Model)
            </div>
    </div>
按计划去做 jQuery Ajax请求能够处理
成功
以及
错误
状态。因此,正确的方法是在出现验证错误时从服务器实际返回一个错误(nothttp200状态)。除非要显示视图,否则不要返回视图。但即使在这种情况下,它们也应该是错误结果的一部分,由不同的客户端功能(
error
handler函数)显示

请在中阅读有关此的所有详细信息。这里也提供了所有的代码,所有的内容都是一步一步地解释的,所以很容易理解

它使用一个自定义异常类,该类在出现任何模型状态错误时抛出;使用该异常并向客户端返回错误的自定义错误操作筛选器。这使得以正确的方式执行Ajax请求变得非常容易:

$.ajax({
    type: "POST",
    data: /* your data */,
    success: function(data, state, xhr) {
        // do wahetever required
    },
    error: function(xhr, state, err) {
        // do something about the error ie. inform the user about it
    }
});
这比在
success
状态中检测错误并在其中包含不必要的分支要好得多。jQuery应该以这种方式使用,而不仅仅是
success
处理程序

旁注
很抱歉,我没有早点看到您的问题,因为我想它提供的信息会让您更高兴。

我的更新部分视图返回索引方法。这个方法填充我的表,比如更新ajax jquery

我喜欢在
PartialView
中只更新mu表。这种情况:

success: function (result) {
    var isValid = $(result).find(".validation-summary-errors").length == 0;

    //If Successful, reload Survey Partial View
    if (isValid) {
         $('#surveyBox').html(result);
    }
    //If Validation Failed reload form with validation errors
    else {
        $('#editSurveyModal').html(result);
    }
}
    <div class="container container-Top">
        <h4>Lista de categorias produtos</h4>
        <p>
            <hr />
            <br />
            @using (Html.BeginForm())
            {
                <div class="form-group">
                    <div class="col-lg-4">
                        @Html.TextBox("NomeCategoria", null, new { @class = "form-control" })
                    </div>
                    @Html.ActionLink("Pesquisar", null, null, new { @class = "btn btn-default", @id = "Pesquisar" })
                </div>
            }                       
            <br />
            <br />
            <br />
            <div id="DvDetalheCategoria" class="form-group">
                @Html.Partial("_DetalhesCategoria", Model)
            </div>
    </div>

产品分类表



@使用(Html.BeginForm()) { @TextBox(“NomeCategoria”,null,new{@class=“form control”}) @ActionLink(“Pesquisar”,null,null,new{@class=“btn btn default”,@id=“Pesquisar”}) }


@Html.Partial(“_detalhesculatia”,模型)
我的Jquery

    <script type="text/javascript">

            $(function () {
                $("#Pesquisar").click(function () {
                    var $btnPesquisar = $(this);
                    var idCategoria = $("#NomeCategoria").val();                
                    $.ajax({
                        url: '@Url.Action("_DetalhesCategoria", "VntCategoria")',
                        data: { pName: idCategoria },
                        type: 'POST',
                        success: function (data) {
                            $("#DvDetalheCategoria").html(data);                        
                        },
                        error: function (ex) {
                            alert('Falha ao carregar categorias' + item.Id);
                        }
                    });
                });
            });
        </script>

$(函数(){
$(“#Pesquisar”)。单击(函数(){
var$btnPesquisar=$(本);
var idCategoria=$(“#NomeCategoria”).val();
$.ajax({
url:“@url.Action”(“详细分类”、“VntCategoria”),
数据:{pName:idCategoria},
键入:“POST”,
成功:功能(数据){
$(“#DvDetalheCategoria”).html(数据);
},
错误:函数(ex){
警报(“Falha ao carregar分类”+项目Id);
}
});
});
});
我的控制器:

     // GET: /VntCategoria/
    public ActionResult Index()
    {
        return View(db.VntCategoriaProdutos.ToList());
    }

    [HttpPost]
    public ActionResult _DetalhesCategoria(string pName)
    {
        ListaCategorias = new List<VntCategoriaProdutos>();
        ListaCategorias = db.VntCategoriaProdutos.ToList().FindAll(f => f.DescricacaoCategoria == pName);
        return View(ListaCategorias);
    }
//获取:/VntCategoria/
公共行动结果索引()
{
返回视图(db.VntCategoriaProdutos.ToList());
}
[HttpPost]
public ActionResult_DetalhesCategoria(字符串pName)
{
ListaCategorias=新列表();
ListaCategorias=db.VntCategoriaProdutos.ToList().FindAll(f=>f.descripacaocategoria==pName);
返回视图(ListaCategorias);
}

你能不能用一个Ajax表单-@Ajax.BeginForm(“操作”、“控制器”)这正是我想要避免的。我想使用模型上的TextBoxFor(..)和属性来利用MVCs验证我的部分代码。这可能就是我最终要做的。看起来有点俗气。我会通知你的。你不能用这种方式利用MVC的验证。这就是我的问题所在。“我如何才能在不进行完整回发的情况下利用MVC验证?”这是为了避免必须用javascript处理验证通知,这很糟糕。这是一个答案吗?在目前的情况下,我不相信