Some Title
Ipsum Lorem
Can I return a Json result that contains also a rendered view?
I need it to return the new ID of a submitted form along with its HTML and some other properties.
I've been thinking about this problem for a while. My solution is similar to returning the partial view HTML as a JSON string, but the opposite. Return a partial view with JSON embedded in it. I did not like this approach until jQuery 1.4.3 merged their .data() method with the HTML 5 data attribute. This makes it much easier to generate JSON within a ASP.NET MVC view, and read it via jQuery.
See example... It isn't perfect, but I like it much better than creating hidden form inputs or helpers that render the partial view before returning it.
Partial View:
Some Title
Ipsum Lorem
JavaScript that reads the JSON
$(document).ready(function () {
var name = $('#dataDiv').data('stuff').name;
var color = $('#dataDiv').data('stuff').color;
alert(name + ' ' + color);
});
This may appear to go against the "single responsibility principle" (if you apply it to views). However, if your application requires both pieces of data to be transmitted in a response, then I see nothing wrong with it. And as long as your model is constructed properly, it won't go against any design principles.