ASP.NET MVC显示成功消息

时间:2011-01-13 19:13:41

标签: c# asp.net-mvc

以下是我从我的应用中删除记录的示例方法:

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

1 个答案:

答案 0 :(得分:18)

一种方法是使用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
}

更新:

示例:

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>