简体   繁体   中英

How to load partialview content and return to ajax result?

I use Ajax :

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

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

            }
        });

and I want to load the whole html from a partial view that take some data from LoadPictureGallery. Anyway to write this properly ?

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

UPDATED: What I need is Render a view as a string

render a partialview to string and return it.

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

You should just be able to return a partialView

return PartialView(model);

And then use data itself

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

Use a PartialViewResult in your action.

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

and just use the raw return data in your javascript

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM