I have a MVC app with quite a few Controller Actions that are called using Ajax (jQuery) and return partial views content which updates a part of the screen. But what I would rather do is return JSON something like this.
return Json(new {
Result = true,
Message = "Item has been saved",
Content = View("Partial")
});
Where the HTML is just a property of the Json. What this means is I need to retrieve the HTML that is rendered by the View method. Is there any easy way to do this, a few examples I have seen are quite convoluted.
Edit: This question was originally for ASP.NET MVC 1, but if version 2 makes it easier I would like to hear the answer.
Here is the answer! It is slight change from Martin From's method and it seems to work. If there are things missing please can people contribute any code changes in the comments section. Thanks.
From you controller call it like this:
Add this to a class
This is a good solution to the problem: http://craftycode.wordpress.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/
I've spent ages trying to do the same thing. I have a quick solution which will need to be extended on.
NOTE: I can see one issue already.. Any cookies and other variables are lost :(
What I did:
Create new ActionResult
The Data class
The controller extensions
Why not just have static html "partials" and grab all the dynamic content from the json? You should be able to load the html files with jquery when the page loads or when needed quite easily.
This link on JQuery Ajax gives this example:
NerdDinner has some pretty good examples of this. Here is the SearchController in NerdDinner, which has a method called SearchByLocation that returns a list of JsonDinners (source code for NerdDinner is Creative Commons):
I am using the HTML Helper from this article: Render partial view to string in ASP.NET MVC. It works perfectly!