我已经看过很多关于这方面的帖子,但我想在沿着我认为我可能需要走的路线之前尝试获得最佳实践。在将新记录插入数据库后,我正在尝试更新视图:
非常基本的设置:
<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({
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 或其他东西,但我想知道是否有办法以这种方式更新视图。