c# - 在索引视图页面中显示插入和更新数据的消息
问题描述
在我的 ASP.NET MVC 应用程序中,我们有
public ActionResult Create(parameters)
{
if (ModelState.IsValid)
{
//code block
return RedirectToAction("Index");
}
}
这是数据插入的方法:
public ActionResult Edit(int? id)
{
if (ModelState.IsValid)
{
//code block
return RedirectToAction("Index");
}
}
而且我还有一种数据编辑方法。
成功插入/编辑后,我正在调用
return RedirectToAction("Index");
我想为方法显示一条消息“数据插入成功”,为create
方法显示“数据更新成功” update
。
是否可以在页面上显示这样的消息Index
,或者有没有其他方法可以向用户显示这两个成功操作的消息?
解决方案
1.将字符串作为模型传递给视图没有问题:
public ActionResult Index(string message)
{
return View((object)message);
}
public ActionResult Create(/*parameters*/)
{
if (ModelState.IsValid)
{
//code block
return RedirectToAction("Index", new { message = "Data inserted successfully" });
}
return View();
}
public ActionResult Edit(int? id)
{
if (ModelState.IsValid)
{
//code block
return RedirectToAction("Index", new { message = "Data updated successfully" });
}
return View();
}
和Index.cshtml
:
@model System.String
@{
ViewBag.Title = "Home Page";
var text = (Model is string) ? Model : String.Empty;
}
@if (!String.IsNullOrEmpty(text))
{
<div class="jumbotron">
<h1>@Model</h1>
</div>
}
@using (Html.BeginForm("Create", "Home" /* route values */))
{
<input type="submit" value="Insert" />
}
@using (Html.BeginForm("Edit", "Home", new { id = 123 }))
{
<input type="submit" value="Update" />
}
2.并且可以在中传递消息TempData
:
public ActionResult Index(string message)
{
TempData["message"] = message;
return View((object)message);
}
在视图中:
@{
var message = (TempData.ContainsKey("message") && TempData["message"] is string msg) ? msg : String.Empty;
ViewBag.Title = "Index Page";
}
@if (!String.IsNullOrEmpty(message))
{
<div class="jumbotron">
<h1>@Model</h1>
</div>
}
3. 强类型视图的视图模型中可能包含消息字符串。
推荐阅读
- c - 如何更改 GtkTreeModel 的数据(在“已编辑”回调中)
- javascript - React - onSubmit 没有任何数据的表单
- matlab - 有什么方法可以矢量化 matlab 代码或其他方法来减少它的运行时间?
- bash - Helm 模板多行秘密值
- r - 为(900+)个节点创建边缘列表(在 R 中)
- javascript - 如何禁用图表ChartJS中的点击
- javascript - Vuetify a la carte:在静态 html 文件中使用时汇总组件抱怨?
- r - r - 在 plot3D 中强制/编辑轴值
- algorithm - 将数学问题转换为动态规划
- python - 此方法用于使用 with_items 循环对变量进行字符串连接是否正确?