在我的ASP.NET MVC應用程式中,我們有
。public ActionResult Create(parameters)
{
if (ModelState.IsValid)
{
//代碼塊
return RedirectToAction("Index"/span>)。
}
}
這是資料插入的方法:
public ActionResult Edit(int? id)
{
if (ModelState.IsValid)
{
//代碼塊
return RedirectToAction("Index"/span>)。
}
}
我也有一個資料編輯的方法。
在成功插入/編輯時,我正在呼叫
。return RedirectToAction("index")。
我想為create方法顯示 "資料插入成功 "的資訊,為update方法顯示 "資料更新成功"。
是否有可能在Index頁面上顯示這樣的資訊,或者有什么其他的方法可以讓我為這兩個成功的操作向用戶顯示資訊?
uj5u.com熱心網友回復:
1. 將一個字串作為模型傳遞給視圖是沒有問題的:
1.
還有 2.而且可以在 在視圖中: 3.強型別視圖的視圖模型中可能包含一個訊息字串。
uj5u.com熱心網友回復: 你可以使用toastr .... 這里有詳細的例子 https://www.c-sharpcorner.com/UploadFile/97d5a6/toastr-notifications-to-your-web-site/ uj5u.com熱心網友回復: 我喜歡使用TempData來傳遞資訊給View。 你可以在RedirectToAction之前設定TempData的值: 在索引視圖中,只有在控制器中設定了TempData的情況下,才會顯示該資訊:
標籤: 上一篇:使用boto3python寫到S3桶中的一個特定檔案夾中
下一篇:腳本。遞回回傳未定義
public ActionResult Index(string message)
{
return View((object)message)。
}
public ActionResult Create(/*parameters*/)
{
if (ModelState.IsValid)
{
//代碼塊
return RedirectToAction("Index", new { message = "Data inserted successfully" })。
}
return View()。
}
public ActionResult Edit(int? id)
{
if (ModelState.IsValid)
{
//代碼塊
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" />
}
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 = "索引頁"。
}
@if (!String.IsNullOrEmpty(message))
{
<div class="jumbotron" >
<h1>@Model</h1>
</div>
}
TempData["message"] = "資料插入成功"。
return RedirectToAction("index")。
@if (TempData["message"] !=null)
{
<div class="alert-info">@TempData["message"] </div>
}
