我有以下ActionResult
in a controller
你可以看到我在ViewBag
如果成功的话。然后在View
如果它不为空,它应该输出该消息。但是,我无法显示该消息,也没有看到问题所在。
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
{
Name = collection["RoleName"]
});
context.SaveChanges();
ViewBag.ResultMessage = "Role created successfully.";
return RedirectToAction("Index");
}
catch (Exception)
{
return View();
}
}
这是我的 Index.cshtml
@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>
@{
ViewBag.Title = "Index";
}
<h2>Roles Listing </h2>
@ViewBag.ResultMessage
@Html.ActionLink("Create New Role", "Create") | @Html.ActionLink("Manage User Role", "ManageUserRoles")
<div>
<table class="table table-bordered table-condensed table-striped table-hover ">
<thead>
<tr>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach (var role in Model)
{
<tr>
<td><strong>@role.Name</strong></td>
<td>
<span onclick="return confirm('Are you sure you want to delete @role.Name?')"><a href="/Roles/[email protected]" class="delLink" style="color:red;">Delete</a></span> |
@Html.ActionLink("Edit", "Edit", new { roleName = @role.Name })
</td>
</tr>
}
</tbody>
</table>
</div>
ViewBag
当您从controller
to view
。寿命短意味着当发生重定向时值变为空。这是因为他们的目标是提供一种相互沟通的方式controllers
and views
。这是服务器调用中的一种通信机制。
既然你正在使用RedirectToAction
, the ViewBag
变成null
当它达到view
.
您可以使用TempData
为了这:
TempData["ResultMessage"] = "Role created successfully.";
It uses Session
作为存储,但在第二次响应后它将不再存在。TempData
当您从一个位置移动时有助于维护数据controller
给其他人controller
或从一个动作到另一个动作。换句话说,当您重定向时,Tempdata
有助于维护这些重定向之间的数据。它在内部使用会话变量。TempData
在当前和后续请求期间使用仅意味着当您确定下一个请求将重定向到下一个视图时使用它。
有关于此的更多理解,请参阅此link
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)