【问题标题】:Index ViewResult not re-rendering after callback from ajax call从 ajax 调用回调后索引 ViewResult 不重新渲染
【发布时间】:2011-12-05 01:39:44
【问题描述】:

我正在尝试从 ajax 调用回调到我的 ViewResult Index() 控制器操作,以根据下拉选择更新页面内容,但我的视图没有重新更新(重新渲染)。

我已经设置了断点,并且控制器中的 index() 操作正在按照从 ajax 'get' 调用的方式执行,并且模型正在传递给视图(视图中也遇到了断点)。

查看:

  @* Contains code to build a webgrid and display data based on the model passed in... *@
  @* Contains a couple of dropdowns for filtering *@
  @* 
     Catch the select event from a dropdown and call back into the view to re-update page contents
     for filter requests.
  *@
    <script type="text/javascript">
        $("select").multiselect({
            click: function (event, ui) {
               $.ajax(
               {   type: "GET",
                   url: '@Url.Action("Index","Data")',
                   data: { FilterRequest: (ui.checked ? 'checked' : 'unchecked') },
                   success: function () {
                   alert('hello again');
               }
             })
            }
        });
</script>

控制器:

// GET: /Data/
public ViewResult Index(string FilterRequest)
{
    IList<DataModel> dataResult;
    if (FilterRequest == null)
    {   // Not a filter request so just update grid with full contents
        dataResult = db.DataObjs.OrderByDescending(x => x.id).ToList();
    }
    else
    {   // Filter request so update grid with filtered data
        dataResult = db.DataObjs.Where(/*Build some filtered stuff here*/).OrderByDescending(x => x.id).ToList();
    }            

    // Build some sub totals based on the resultset from above result set to display
    // Other business logic number mashing here to display in other grids on the same view

    return View(dataResult);
 }

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-3 jquery


    【解决方案1】:

    您没有对$.ajax 调用的响应做任何事情。

    类似这样的:

    $.ajax(
    {   
       type: 'GET',
       url: '@Url.Action("Index","Data")',
       data: { FilterRequest: (ui.checked ? 'checked' : 'unchecked') },
       dataType: 'html',
       success: function (html) {
          $('#somecontainer').html(html);
       } 
    });
    

    此外,您不能从您的操作方法返回完整视图(例如 HTML 页面) - 您需要返回 PartialViewJsonResult,您可以对其进行迭代并手动绑定内容。

    对于局部视图,您需要这样的东西:

    return PartialView(dataResult);
    

    这完全取决于您尝试重新渲染的内容。如果需要重新渲染的 HTML 很复杂,请使用局部视图。如果只是将一堆数据推入输入元素(例如下拉列表),则应通过网络保存 HTTP 有效负载并使用JsonResult

    【讨论】:

    • 感谢您的回复。我在我的控制器方法中进行了一些计算,我的视图进行格式化和查找(从 id 到字符串文字)并显示多个网格,这就是我想通过 Index 方法进入的原因。所以,我会尝试部分视图路线。也就是说,我想我可以用过滤后的结果构建一个 json 结果,但是如何将它绑定到已经存在的网格(尚未过滤的网格)?
    • @Jaj - 不确定,这取决于您如何实现网格。从局部视图开始,然后从那里开始。你也可以使用$.get 而不是$.ajax 来简化你的JS代码。
    • 我无法让 html() 方法工作,但我确实有一些运气 $('#gridview').load('@Url.Action("Filter")', data ) 但不是 webgrids。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多