2011-01-13 7 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"); 
} 

は次のように述べていIndexビューにメッセージを表示しています: "Lorem ipsumの記事が削除されました"どうすればいいですか?おかげ

ここでは私の現在のIndexメソッドで、念のため:TempDataをを使用することです

// 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パッケージを作成しました/ packages/BootstrapNotifications/ –

答えて

18

一つの方法:

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

、あなたはTempDataをからこのメッセージをフェッチすることができIndexアクション内部それを利用する。たとえば、あなたはそれを表示できるように、ビューに渡されることになる、あなたのビューモデルのプロパティとしてそれを渡すことができます。

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

と強く型付けされたビュー内:https://www.nuget.org:

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

面白いようですね。 1.)ビューにどのように渡しますか。 2.)どのようにViewに表示するのですか?ありがとう:) – Cameron

+0

このメッセージに割り当てられる文字列プロパティを持つViewModelを定義します。次に、このビューモデルにビューを強く入力し、ビューの中で単に '<%:Model.Message%>'を使用します。または、コントローラのアクション 'ViewData [" message "] = message;'とビューの内部で、非常に醜い何かをします: '<%:ViewData [" message "]%>'(私はこれを繰り返します。それをお勧め、ViewDataちょうど吸う)。 –

+0

私はViewModelをよく理解しておらず、強くタイプしています。上のコードに例を示すことができますか?ありがとう。 – Cameron

関連する問題