ASP.NET MVC 显示成功消息

2024-03-16

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

[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");
}

我想做的是在索引视图上显示一条消息,内容如下:“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 获取此消息并使用它。例如,您可以将其作为视图模型的属性传递,该属性将传递给视图,以便它可以显示它:

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

UPDATE:

Example:

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

进而:

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

在强类型视图内部:

<div><%: Model.Message %></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET MVC 显示成功消息 的相关文章

随机推荐