在我的 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,或者有沒有其他方法可以向用戶顯示這兩個成功操作的訊息?
uj5u.com熱心網友回復:
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. 強型別視圖的視圖模型中可能包含訊息字串。
uj5u.com熱心網友回復:
您可以使用 toastr .... 這是詳細的示例
https://www.c-sharpcorner.com/UploadFile/97d5a6/toastr-notifications-to-your-web-site/
uj5u.com熱心網友回復:
我喜歡使用TempData將訊息傳遞給視圖。您可以在 RedirectToAction 之前設定TempData的值:
TempData["message"] = "data inserted successfully";
return RedirectToAction("Index");
在 Index 視圖中,只有在控制器中設定了TempData時才會顯示該訊息:
@if (TempData["message"] != null)
{
<div class="alert-info">@TempData["message"]</div>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/422234.html
標籤:
上一篇:方法被呼叫兩次
