在.NET MVC中使用JSON参数返回视图并更新DOM

时间:2017-07-02 15:50:01

标签: javascript jquery asp.net json asp.net-mvc

我有一个.NET动作,基本上会返回一组JSON结果,如下所示:

 return Json(new
 {
   lineData = groupedByDate,
  // more properties returned here...
   dataForTable = View("Index") // note this one
  }, JsonRequestBehavior.AllowGet);

在返回功能之前,我为我的ViewBag设置了数据源,这是我的表格的数据来源,如下所示:

ViewBag.Items = items.ToList();

在我看来:

<table id="tableProducts" class="table table-striped table-hover table-fw-widget">
       <tbody>
       @if (ViewBag.Items != null)
       {
        foreach (var item in ViewBag.Items)
        {
           <tr>
                  <td>@item.Title//for example</td>                                                                      
           </tr>
        }
       }
       </tbody>
</table>

以下是我不能为我工作的部分...我实际上在我的.done方法中设置了json值,如下所示:

($.post...).done(function(data){
graph.SetData(data.lineData); // this is fine
And now I would like to simply inject the returned view here as well in the DOM.. Like this:

    var products= $('<table />').append(data.dataForTable).find('#tableProducts').html();
    $('#tableProducts').html(products);

});

所以这就是问题所在:

 var products= $('<table />').append(data.dataForTable).find('#tableProducts').html();
        $('#tableProducts').html(products);

我希望将视图的返回部分注入到DOM中,但是当我执行此操作时没有任何反应......表格仍然是空的,因为它在开头...

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

如果你想实现这种功能,那么你可以使用以下流程:

1)为html创建部分视图

2)使用某个函数

将部分视图转换为html字符串

3)将该字符串传递给json参数

4)使用ajax调用方法

5)在ajax成功中,你可以将你的html字符串替换为你想要的地方

Check this link for reference