0

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();
        }
    }
Community
  • 1
  • 1
nam vo
  • 3,271
  • 12
  • 49
  • 76
  • "*Anyway to write this properly ?*" I think your question is a bit vague. If you don't get answers that fully answer your question you might need to reword it to better outline your problem. – Rowan Freeman Mar 24 '14 at 04:33
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Mar 24 '14 at 04:34

2 Answers2

0

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);
},
KJ3
  • 5,168
  • 4
  • 33
  • 53
0

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);
}
SlightlyMoist
  • 882
  • 5
  • 7