如何加载部分视图内容并返回到ajax结果?

时间:2014-03-24 04:22:32

标签: c# asp.net-mvc

我使用Ajax:

$.ajax({
            url: url,
            data: request,
            dataType: "json",
            success: function (data) {

                $(".ad-image-wrapper").html(data.html);
            },
            error: function () {

            }
        });

我希望从部分视图加载整个html,从LoadPictureGallery获取一些数据。无论如何要正确地写这个?

 public ActionResult LoadPictureGallery(string xxx)
    {
        var model = List<ABCClass>(){ blah blah};
        return new JsonResult() { html= XXXPartialView(model), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

更新:我需要的是Render a view as a string

将部分视图渲染为字符串并将其返回。

 public ActionResult LoadPictureGallery(string url, string alt)
    {

        var picture = new PictureModel()
        {
            ImageUrl = url,
            AlternateText = alt,
            FullSizeImageUrl = url,
            Title = alt
        };
        return new JsonResult() { Data = RenderRazorViewToString("_PhotoItem", picture), JsonRequestBehavior = JsonRequestBehavior.AllowGet };


    }

public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

2 个答案:

答案 0 :(得分:0)

您应该能够返回部分视图

return PartialView(model);

然后使用数据本身

success: function (data) {
    $(".ad-image-wrapper").html(data);
},

答案 1 :(得分:0)

在您的操作中使用PartialViewResult

public PartialViewResult LoadPictureGallery(string xxx)
{
    var model = List<ABCClass>(){ blah blah};
    return PartialView(model);
}

只需使用javascript中的原始返回数据

success: function (data) {
      $(".ad-image-wrapper").html(data);
}