在索引视图页面中显示插入和更新数据的消息

Posted

技术标签:

【中文标题】在索引视图页面中显示插入和更新数据的消息【英文标题】:Show message for insert and update data in index view page 【发布时间】:2021-11-02 16:39:18 【问题描述】:

在我的 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】:

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.消息字符串可能包含在强类型视图的视图模型中。

【讨论】:

【参考方案2】:

您可以使用 toastr .... 这是带有详细信息的示例

https://www.c-sharpcorner.com/UploadFile/97d5a6/toastr-notifications-to-your-web-site/

【讨论】:

【参考方案3】:

我喜欢使用 TempData 将消息传递给视图。您可以在 RedirectToAction 之前设置 TempData 的值:

TempData["message"] = "data inserted successfully";
return RedirectToAction("Index");

在索引视图中,只有在控制器中设置了 TempData 时才会显示消息:

@if (TempData["message"] != null)

    <div class="alert-info">@TempData["message"]</div>

【讨论】:

以上是关于在索引视图页面中显示插入和更新数据的消息的主要内容,如果未能解决你的问题,请参考以下文章

Vue使用v-for显示列表时,数组里的item数据更新,视图中列表不同步更新的解决方法

RedirectToAction在控制器中工作,但不更新视图和URL

旋转设备时表格视图更新无效

关系数据库标准语言SQL02

如何以通量模式存储对象更新视图

应更新数据时,NSManagedObject 的删除/插入与更新