2011-01-13 53 views
11

下面是一个例子方法,我有一个从我的应用程序中删除一条记录: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 
    [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); 
    } 
+0

我创建了一个NuGet包与发送从控制器(错误,警告,信息和成功)消息有助于查看的引导准备:https://www.nuget.org/packages/BootstrapNotifications/ – 2014-06-23 15:12:34

回答

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 
} 

UPDATE:

例子:

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> 
+0

好吧,听起来很有趣。 1.)我如何将它传递给视图。 2.)我如何在视图中显示它。谢谢:) – Cameron 2011-01-13 19:29:52