gpt4 book ai didi

c# - ASP.NET MVC 显示成功消息

转载 作者:可可西里 更新时间:2023-11-01 08:40:01 25 4
gpt4 key购买 nike

这是我从我的应用程序中删除记录的示例方法:

[Authorize(Roles = "news-admin")]
public ActionResult Delete(int id)
{
var ArticleToDelete = (from a in _db.ArticleSet where a.storyId == id select a).FirstOrDefault();
_db.DeleteObject(ArticleToDelete);
_db.SaveChanges();

return RedirectToAction("Index");
}

我想做的是在索引 View 上显示一条消息,内容如下:“Lorem ipsum 文章已被删除”我该怎么做?谢谢

这是我当前的 Index 方法,以防万一:

    // INDEX
[HandleError]
public ActionResult Index(string query, int? page)
{
// build the query
var ArticleQuery = from a in _db.ArticleSet select a;
// check if their is a query
if (!string.IsNullOrEmpty(query))
{
ArticleQuery = ArticleQuery.Where(a => a.headline.Contains(query));
//msp 2011-01-13 You need to send the query string to the View using ViewData
ViewData["query"] = query;
}
// orders the articles by newest first
var OrderedArticles = ArticleQuery.OrderByDescending(a => a.posted);
// takes the ordered articles and paginates them using the PaginatedList class with 4 per page
var PaginatedArticles = new PaginatedList<Article>(OrderedArticles, page ?? 0, 4);
// return the paginated articles to the view
return View(PaginatedArticles);
}

最佳答案

一种方法是使用 TempData:

[Authorize(Roles = "news-admin")]
public ActionResult Delete(int id)
{
var ArticleToDelete = (from a in _db.ArticleSet where a.storyId == id select a).FirstOrDefault();
_db.DeleteObject(ArticleToDelete);
_db.SaveChanges();
TempData["message"] = ""Lorem ipsum article has been deleted";
return RedirectToAction("Index");
}

Index 操作中,您可以从 TempData 获取此消息并使用它。例如,您可以将它作为 View 模型的属性传递,该属性将传递给 View ,以便它可以显示它:

public ActionResult Index()
{
var message = TempData["message"];
// TODO: do something with the message like pass to the view
}

更新:

例子:

public class MyViewModel
{
public string Message { get; set; }
}

然后:

public ActionResult Index()
{
var model = new MyViewModel
{
Message = TempData["message"] as string;
};
return View(model);
}

在强类型 View 中:

<div><%: Model.Message %></div>

关于c# - ASP.NET MVC 显示成功消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4684196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com