8

フォームを含むポップアップ ウィンドウがあるとします。フォームを処理するコントローラーが必要です。結果に応じて、このコントローラーは JSON (すべてがうまくいき、JavaScript でポップアップを閉じることができる場合) または HTML (フォーム データが無効でフォームを置き換える必要がある場合) を返します。新しい html を使用 - 検証エラー メッセージを使用)。だから私はまさにそのような解決策を見つけました:それはフォームです:

<form id="message" ...>
    ...
</form>

そして、私はこのフォームのjqueryハンドラを持っています:

$(document).on("submit", "form#message", function (evt) {
    evt.preventDefault();
    $.ajax({
        type: this.method,
        url: this.action,
        data: $(this).serialize(),
        success: function (result) {
            if ($.isPlainObject(result)) {
                // this is JSON
                // close the pop-up window
            } else {
                // this is HTML
                $("form#message").html(result);
            }
        }
    });
});

コントローラ:

[HttpPost]
public ActionResult UpdateMessage(MessageModel model)
{
    ...
    if (.. is valided ..)
        return Json(new { success = "OK" });
    else
        return View(model);
}

質問 - そのようなタスクのためのより洗練されたソリューションはありますか?

4

3 に答える 3

5

IMHOこれは、この問題に対する非常に優れた解決策であり、私が間違いなく使用するものです。

于 2013-05-21T06:21:17.533 に答える
2

あなたのアプローチでうまく見えます。ただし、使用するすべての画面で JSON エラー メッセージが共通である場合は、アクション フィルターを作成することをお勧めします。コードをよりエレガントにすることができます

[HttpPost]
[JsonErrorHandling]
public ActionResult UpdateMessage(MessageModel model)
{    
    return View(model);
}

public class JsonErrorHandlingAttribute : ActionFilterAttribute, IActionFilter 
{
   void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
   {
      // TODO: doing some thing magic here
      // if (.. is valided ..)
      //  return Json(new { success = "OK" });

      this.OnActionExecuting(filterContext);
   }
}
于 2013-05-21T07:13:11.437 に答える