【问题标题】:Returning the view with JSON parameters in .NET MVC and updating the DOM在 .NET MVC 中返回带有 JSON 参数的视图并更新 DOM
【发布时间】:2017-07-02 15:50:01
【问题描述】:

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

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

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

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 中,但是当我这样做时没有任何反应...该表仍然是空的,因为它在开始时...

我在这里做错了什么?

【问题讨论】:

  • 检查ajax请求,看看从服务器返回的json是否是你所期望的。
  • @Shyju 它说:Object {MasterName: "", Model: null, TempData: Array(0), View: null, ViewBag: Object...}MasterName: ""Model: nullTempData: Array (0)View: nullViewBag: ObjectViewData: Array(2)ViewEngineCollection: Array(2)ViewName: "Index"proto: Object
  • @Shyju 看起来视图为空?
  • 也许我应该说明我的观点的路径或类似的东西?
  • 有人吗??? =)

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


【解决方案1】:

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

1) 为 html 创建局部视图

2) 使用某些函数将部分视图转换为 html 字符串

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

4) 使用ajax调用方式

5) 在 ajax 成功中,您可以将 html 字符串替换到任何您想要的地方

Check this link for reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 2011-02-19
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2015-06-13
    相关资源
    最近更新 更多