2017-07-03 12 views
0

私はASP.NET MVCウェブ開発の新品です。 そして、私は基本的にユーザーが入力できるデータベースにアクセスできるウェブサイトを構築しようとしています。ViewBagのコンテンツが可視化されていません

申し分なく、すべていいです、その部分はうまく動作します。私が苦労しているのは、ユーザーがデータをデータベースに挿入するたびに、挿入が成功したかどうかを示すメッセージを表示することです。私はそれをフォームパネルに表示したい。

これは私がこれまでに得たコードです:

をこれは、ユーザーが送信ボタンをクリックしたときに呼び出されるメソッドです:

[HttpPost] 
public ActionResult Create(PersonModels person) 
{ 
    try 
    { 
     // TODO: Add insert logic here 
     //Adding to database and holding the response in the viewbag. 
     string strInsertion = ConnectionModels.insertPerson(person); 
     ViewBag.InsertionResult = strInsertion; 

     return RedirectToAction("Index"); 
    } 
    catch 
    { 
     return View("Index"); 
    } 
} 

そして、これが私のindexアクションです:

public ActionResult Index() 
{ 
    return View(); 
} 

最後に、これは私がindex.cshtmlに入れようとしていることです:

<div> 
    <label> 
     @ViewBag.InsertionResult 
    </label> 
</div> 

私は完全に投稿するつもりはありません。しかし、これはフォームパネルのdivの下にあります。

私に手を差し伸べていただければ幸いです。

ありがとうございます! :)

+1

正確な質問:https://stackoverflow.com/questions/14497711/set-viewbag-before-redirect –

答えて

3

ViewBag値を渡して別のアクションにリダイレクトすることはできません。

return RedirectToAction("Index", new {message="Your Message"}); 

し、このようにそれを取り戻す:

public ActionResult Index(string message) 
{ 
    ViewBag.ViewBag.InsertionResult = message; 
    return View(); 
} 
あなたが同じコントローラである場合は、それ以外の場合は、あなたが以下のように RedirectionResultにパラメータとしてメッセージを渡すことができますセッションに値を渡すために TempDataを使用することができます

これは、メッセージを渡す方法を一般的な方法ですが、私はこのような何かをお勧めします:

は、すべてのコントローラはこの1つから継承BaseControllerを使用します

エラーメッセージ、通知メッセージ、情報メッセージなどのグローバルメッセージを処理する方法をカスタムロジックで作成できます。私はここでそれをシンプルに保管しております

:で

public abstract class BaseController : Controller 
{ 
    protected GlobalMessage GlobalMessage; 
    protected override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     if (filterContext.Result is ViewResult) 
     { 
      if (GlobalMessage!= null) 
      { 
       filterContext.Controller.ViewBag.GlobalMessage = GlobalMessage; 
      } 
      else 
      { 
       GlobalErrorViewModel globalErrorModelView = TempData["GlobalMessage"] as GlobalMessage; 

       if (globalErrorModelView != null) 
       { 
        filterContext.Controller.ViewBag.GlobalErrorViewModel = globalErrorModelView; 
       } 
      } 
     } 
     base.OnActionExecuted(filterContext); 
    } 

} 

BaseController

public class GlobalMessage 
{ 
    public string Message { get;set;} 
    public AlertType AlertType {get;set;} 
} 
public enum AlertType 
{ 
    Success, Info, Error, Danger//etc 
} 

あなたはこのようなものを持っているでしょう以下のようなものについては

あなたがモデルを作成する必要がありますこの瞬間に Tempdataに新しい GlobalMessageを登録する必要があります。

public PeopleController : BaseController 
{ 
    [HttpPost] 
    public ActionResult Create(PersonModels person) 
    { 
     try 
     { 
      // TODO: Add insert logic here 
      //Adding to database and holding the response in the viewbag. 
      string strInsertion = ConnectionModels.insertPerson(person); 
      TempData["GlobalMessage"] = new GlobalMessage{ AlertType = AlertType.Info, Message = "You have successfully added a new person" } 

      return RedirectToAction("Index"); 
     } 
     catch 
     { 
      return View("Index"); 
     } 
    } 
} 

次に、ここでは、ビュー内のデータを表示する方法の最終ステップです:

私は個人的にこれを行うには、ポップアップまたはモーダルウィンドウを使用します。

GlobalMessage globalMessage = ViewBag.GlobalMessage as GlobalMessage; 
    @if (globalMessage != null) 
    { 
     <!-- Modal --> 
     <div class="modal fade" id="globalMessage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> 
      <div class="modal-dialog"> 
       <div class="modal-content [email protected] .AlertType.ToString().ToLower() remove-border-radius"> 
        <div class="modal-header panel-heading"> 
         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
        </div> 
        <div class="modal-body"> 
         <p class="h-text-primary">@Html.Raw(globalMessage .Message)</p> 
        </div> 
        <div class="modal-footer"> 
         <button type="button" class="btn [email protected] .AlertType.ToString().ToLower() remove-border-radius" data-dismiss="modal">Close</button> 
        </div> 
       </div><!-- /.modal-content --> 
      </div><!-- /.modal-dialog --> 
     </div><!-- /.modal --> 
    } 
:bootstrappの例では、あなたがこのような何かを書きます

トリガーメッセージがある場合、モーダル:

@if (globalMessage != null) 
{ 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $('#globalMessage').modal('show'); 
     }); 
    </script> 
} 

この例では、異なるメッセージを表示するシステムを作ることができる方法を示すことでした。短期間であなたが欲しいものは何でも!

+0

ダング、これは本当に役に立ちました!どうもありがとう! :D – RottenCheese

+0

私は助けてうれしいです:) –

0

ViewBagおよびViewDataオブジェクトはリダイレクト後にnullの値を返します。それらの内容は、現在の要求の期間だけ存続します。

内容現在とその後の要求が、のみ後続の要求に耐えます別のプロパティ、TempDataは、あります。ただし、RedirectToActionに電話すると、データを渡すことができます。

[HttpPost] 
public ActionResult Create(PersonModels person) 
{ 
    try 
    { 
     // TODO: Add insert logic here 
     //Adding to database and holding the response in the viewbag. 
     string strInsertion = ConnectionModels.insertPerson(person); 
     TempData[InsertionResult] = strInsertion; 

     return RedirectToAction("Index"); 
    } 
    catch 
    { 
     return View("Index"); 
    } 
} 

[HttpGet] 
public ActionResult Index() 
{ 
    string strInsertion = TempData[InsertionResult]; 
    return View("Index", new { InsertionResult = strInsertion }); 
} 

<label> 
    @Model.InsertionResult 
</label> 

良い説明はここで与えられます。http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications/

別のアプローチは、データベース内の人物を作成しHttpPostの結果を含むオプションのビューモデルを取るためにあなたのIndexビューのためになります。そのモデルを使用して、ラベルの内容を入力することができます。強く型付けされたモデルFTW!

関連する問題