更新从AJAX Post, MVC 5添加记录的网格

本文关键字:添加 加记录 网格 MVC AJAX Post 更新 | 更新日期: 2023-09-27 18:10:06

我已经看过不少关于这方面的帖子,但我想在走我可能需要走的路线之前试着得到一个最佳实践。我试图更新我的视图后,我已经插入了一个新的记录到数据库:

非常基本的设置:

<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>

My c# code

// 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 POST

$.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"
});

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

从我所看到的,我需要运行插入,再次抓取所有角色,并在"success"事件中更新网格。这是真的吗?还是有更传统的MVC方式通过ASP.net来实现?显然,我可以沿着使用Knockout或其他东西的路径走到那个程度,但我想知道是否有一种方法来更新这种方式的视图

更新从AJAX Post, MVC 5添加记录的网格

您的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);
  }
}

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

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?
});

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

在ajax调用中添加成功函数,并将其放在

下面

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

你所需要做的就是使用

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,然后追加上述方式。