ASP.NET MVC 3.0使用Partial操作和jQuery ajax更新表单的元素content.html



我在Partial A中有Partial A1

我需要在单击A1B按钮时呈现部分视图A1

为此,我有一个部分视图动作,其参数类型为部分视图A(因为对A有一些依赖关系)

public PartialViewResult A1Partial(A model)
{
    //Getting my deserialized model here successfully
    //doing changes in the model collections
    return PartialView("A1Partial", model);
}

我有onclick函数来调用我的A1Partial部分操作:

$(document).ready(function () {
    $("#A1B").click(function () {
        dataString = $("#myForm").serialize();
        $.ajax({
            type: "POST",
            url: "/Controller/A1Partial",
            data: dataString,
            dataType: "json",
            success: function (data) { 
                            //not working here
                            $("#myDiv").html("");
                $("#myDiv").html(data); 
            }
        });
        return false;
    });
});

我从jQueryajax调用工作正常,dataString在控制器中被反序列化,没有任何问题。

但我在$("#myDiv").append(data);中没有得到任何东西,看起来html没有通过。

我需要做什么改变才能让它发挥作用?

您指示您期望JSON响应类型:

dataType: "json"

然而,你试图把它当作HTML:来使用

$('#myDiv').append(data);

因此,从AJAX请求中删除这个dataType: 'json',在成功回调中,数据变量将表示A1Partial返回的HTML。

您必须在服务器上呈现部分视图,然后通过Json发送HTML结果,如下所示:

public static class Renders
{
    public static string RenderPartialView(this Controller controller, string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
        controller.ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            return sw.GetStringBuilder().ToString();
        }
    }
}

在控制器中:

public JsonResult A1Partial(A model)
{
    //Getting my deserialized model here successfully
    //doing changes in the model collections
    return Json(new
    {
        Html = this.RenderPartialView("A1Partial", model)
    }, JsonRequestBehavior.AllowGet);
}

然后在JQuery代码中:

$("#myDiv").html(data.Html);

最新更新