ASP.NET MVC - Combine Json result with ViewResult

后端 未结 4 496
梦如初夏
梦如初夏 2020-12-02 10:06

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.

4条回答
  •  心在旅途
    2020-12-02 10:32

    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.

提交回复
热议问题