【问题标题】:Update grid with added record from AJAX Post, MVC 5使用来自 AJAX Post、MVC 5 的添加记录更新网格
【发布时间】:2015-11-22 15:07:36
【问题描述】:

我已经看过很多关于此的帖子,但我想在沿着我认为我可能需要走的路线之前尝试获得最佳实践。在将新记录插入数据库后,我正在尝试更新视图:

非常基本的设置:

<table id="grid-basic" class="table table-condensed table-hover table-striped">
    <thead>
        <tr>
            <th data-column-id="role_id">ID</th>
            <th data-column-id="description">Description</th>
            <th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Id</td>
                <td>@item.Name</td>
            </tr>
        }
    </tbody>
    <tfoot>
        <tr>
            <td></td>
            <td style="padding-right: 20px;">
                <div id="add-role-text-group" class="form-group">
                    <input id="add-role-text" type="text" class="form-control input-md" placeholder="Add Role" data-container="body" title="A role description must be entered."/>
                    <span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>
                </div>
            </td>
            <td style="vertical-align: middle;"><button type="button" class="btn btn-xs btn-default command-add"><span class="fa fa-plus"></span></button></td>
        </tr>
    </tfoot>
</table>

我的 C# 代码

// GET: Application Role Management
        [Route("role")]
        public ActionResult Role()
        {
            return View(RoleManager.Roles.ToList<IdentityRole>());
        }

        [HttpPost]
        [Route("addrole")]
        public async Task<ActionResult> AddRole(string description)
        {
            IdentityRole role = new IdentityRole();
            role.Name = description;

            var result = await RoleManager.CreateAsync(role);
            if (result.Succeeded)
            {
                return RedirectToAction("role");
            } else {
                return RedirectToAction("Error");
            }
        }

AJAX 发布

$.ajax({
     type: "POST",
     url: "@Url.Action("AddRole")", // the method we are calling
     contentType: "application/json; charset=utf-8",
     data: JSON.stringify({ description: $element.val() }),
     dataType: "json"
});

我加载视图,抓取系统中的所有角色并显示到网格中。我有一个用于插入新角色的内联行。我输入新角色,单击加号按钮。它发布到 AddRole 路由。我现在如何更新模型和更新网格?

据我所见,我需要运行插入,再次抓取所有角色,并在“成功”事件中更新网格。这是真的?或者是否有更传统的 MVC 方式通过 ASP.net 执行此操作?显然,我可以在某种程度上使用 Knockout 或其他东西,但我想知道是否有办法以这种方式更新视图。

【问题讨论】:

  • 你在为你的表使用 jquery 插件吗?
  • 使用引导网格 - github.com/rstaib/jquery-bootgrid
  • 不熟悉 bootgrid,但 documentation 似乎有一个 append 方法,我认为它是用于添加新行
  • 我在问是否有办法从服务器端更新模型。我正在重定向以再次加载视图,但没有任何反应。我认为那是因为我已经在 POST 中做到了,而这不可能发生。但我不完全确定。
  • 您的编辑显示您使用 ajax 发布,因此您的 POST 方法中的 return RedirectToAction() 毫无意义(ajax 调用不会重定向)并且无论如何您已指定 dataType: "json"。将您的方法更改为return Json(...);(您可能想要返回您刚刚创建的角色的ID?)。您已经知道description,因此您应该能够使用 bootgrid append() 方法根据返回的 ID 和文本框的值添加新行。

标签: c# ajax asp.net-mvc asp.net-mvc-5 jquery-bootgrid


【解决方案1】:

如果你想在添加角色后重新加载当前页面你可以做一件事,

在ajax调用中添加成功函数,如下所示

success:function(){
     window.location.href ="your current page url"
}

【讨论】:

    【解决方案2】:

    您的 POST 方法正在尝试重定向到另一个操作方法,但 ajax 调用不重定向。更改您的方法以返回新角色 Id 值并将其作为 json 返回到视图

    [HttpPost]
    [Route("addrole")]
    public async Task<ActionResult> AddRole(string description)
    {
      IdentityRole role = new IdentityRole();
      role.Name = description;
      var result = await RoleManager.CreateAsync(role);
      if (result.Succeeded)
      {
        return Json(role.Id);
      } else {
        return Json(null);
      }
    }
    

    然后根据文本框的值和返回的Id值修改你的ajax在成功回调中添加新角色

    var description = $('#add-role-text').val();
    var url = '@Url.Action("AddRole")';
    var table = $('#grid-basic');
    $.post(url, { description: description }, function(id) {
      if (!id) { 
        // oops 
        return;
      }
      var newRow = [{ role_id: id, description: description }];
      table.bootgrid("append", newRow);
    }).fail(function() {
      // oops - display error message?
    });
    

    【讨论】:

      【解决方案3】:

      你需要做的就是使用

      return Json(role.Id,JsonRequestBehavior.AllowGet);
      

      然后在你的 ajax 调用中说...

      success:function(data){
       if(data.Id>0){
        $("#grid-basic").append('<tr><td>data.Id</td><td>//description comes here</td></tr>');
       }
       else{
        alert("error");
       }
      }
      

      如果是关于更新表格,那么您可以在表格中追加一行
      上述方式,或者您可以重新加载页面,否则您可以返回部分视图,然后将其附加到 div。最好返回一个Json,然后按照上面的方式追加。

      【讨论】:

      • 因为 OP 正在使用 Bootgrid。这只是为新行添加了 html,并没有广告 Bootgrid 使用的所有其他必要数据(用于搜索、排序等) Bootgrid 有一个特定的 append() 方法来添加新行(请参阅我的答案)。而且您还没有说明如何添加描述。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多