Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

jquery - Partial Views vs. Json (or both)

I use ASP.NET MVC with jQuery and have a lot of Ajax requests to my controllers.

Use Partial Views (usercontrols) to build the intial view when a page is loaded. Then if I need to append/replace data based on my Ajax request I build HTML from the Json response.

This approach gives me full control, ie. I can get extra information back from my controller if something went wrong, and then show an error message based on that.

However, recently I've been really annoyed with all the extra work that goes into maintaining HTML structure both in my partial views and the part that generates HTML from Json.

I like to make a jQuery ajax request and then have the controller return PartialView("mypartialview") and then just use jQuery to replace to HTML in the view.

However, this way I cannot attach extra data from the controller - it's either whatever the partial view gives me - or nothing. At least that's my current take on it.

If some validation goes wrong at some point in my controller action I don't want to return the HTML of the partial view.

So how do you go about handling this issue?

Thanks for reading.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Based on this stackoverflow anwser I have just set out to do the same thing.

First create an extension method for the controller class.

public static string RenderViewToString(this Controller controller, string viewName, object model)
{
    using (var writer = new StringWriter())
    {
         var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
         controller.ViewData.Model = model;
         var viewCxt = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer);
         viewCxt.View.Render(viewCxt, writer);
         return writer.ToString();
     }
}

Then return the json in the controllers action method.

return Json(new {
  Html = this.RenderViewToString("MyView", model),
    SomeExtraData = data
});

Your ajax requests will now receive json with the html contained in it. Still experimenting with this approach over returning plain Html fragments.

Hope that helps.

EDIT Updated to work with razor


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...