ASP.NET MVC - Combine Json result with ViewResult

后端 未结 4 497
梦如初夏
梦如初夏 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:52

    In the first case, I think you can just return HTML, but embed the data in the returned form. Use jQuery to access the data in your success callback.

    $.ajax({
        url: '<%= Url.Action( "MyAction" )',
        dataType: 'html',
        data: $('form').serialize(),
        success: function(data) {
                    $('form').html(data);
                    var id = $('form').find('input#formId[type=hidden]').val();
                 }
    });
    

    In the second case, a shared View that takes two or more ViewNames and uses RenderPartial is probably a better solution that returning HTML through JSON.

    Multiview.aspx

     ...
    <% foreach (string viewName in Model.Views)
       {
           Html.RenderPartial( viewName );
       }
    %>
    

    Then in your action:

    public ActionResult MyAction(...)
    {
         ... set up model with data
         model.Views = new List { "View1", "View2" };
    
         return View( "Multiview", model );
    }
    

提交回复
热议问题