2011-01-13 59 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