1

次のように、コントローラーにインデックスアクションがあります...

public ActionResult Index(string errorMsg = "")
   {
      //do stuff
      ViewBag.ErrorMsg=erorMsg;

      return View();
   }

インデックスの http 投稿である別のアクションがあります。

何か問題が発生した場合、インデックス ページをリロードしてエラーを表示したい...

私は既に条件付きで errorMsg を表示しているビューを持っています。しかし、Index を呼び出してエラー文字列を渡す方法がわかりません。

4

3 に答える 3

4

通常、2 つのアクション間でビューを共有するだけです。次のようなアクションがあると思います(インデックスの機能について提供する情報が多いほど、私の例は良くなります):

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

[HttpPost, ActionName("Index")]
public ActionResult IndexPost()
{

    if (!ModelState.IsValid)
    {
        ViewBag.ErrorMsg = "Your error message"; // i don't know what your error condition is, so I'm just using a typical example, where the model, which you didn't specify in your question, is valid.
    }

    return View("Index");
}

そしてIndex.cshtml

@if(!string.IsNullOrEmpty(ViewBag.ErrorMsg)) 
 {
      @ViewBag.ErrorMsg
 }

 @using(Html.BeginForm())
 {
     <!-- your form here. I'll just scaffold the editor since I don't know what your view model is -->
    @Html.EditorForModel()

    <button type="Submit">Submit</button>
 }
于 2012-10-25T22:54:04.313 に答える
0

あなたが正しく理解している場合は、クエリ文字列に errorMsg を含む URL をヒットするだけです。

/*controllername*/index?errorMsg=*errormessage*

ただし、何か問題が発生した場合、必ずしもページをリロードする必要はありません。これに間違った方法でアプローチしているようです..?

于 2012-10-25T22:53:49.510 に答える
0

RedirectToActionerrorMsg 値のクエリ文字列を使用して、ページにリダイレクトするために使用できます。

[HttpPost]
public ActionResult Index(YourViewModel model)
{
  try
  {
    //try to save and then redirect (PRG pattern)
  }
  catch(Exception ex)
  {
    //Make sure you log the error message for future analysis
    return RedirectToAction("Index",new { errorMs="something"}
  }
}

RedirectToActionリクエストを発行しGETます。HTTP は statelessであるため、フォームの値はなくなります。フォームの値をそのままフォームに残したい場合は、投稿されたビューモデル オブジェクトを再度返します。ViewBag を取り除きErrorMsg、ViewModel に呼び出される新しいプロパティを追加して、その値を設定します。

[HttpPost]
public ActionResult Index(YourViewModel model)
{
  try
  {
    //try to save and then redirect (PRG pattern)
  }
  catch(Exception ex)
  {
    //Make sure you log the error message for future analysis
    model.ErrorMsg="some error";
    return View(model);
  }
}

ビューでは、このモデルのプロパティを確認して、ユーザーにメッセージを表示できます。

于 2012-10-25T22:54:17.867 に答える