簡體   English   中英

在Html.BeginForm MVC中處理異常

[英]Handle exception in Html.BeginForm MVC

我在視圖中有一個標有@ html.beginForm的表單。 該表格由下拉菜單,文本框和按鈕組成。 下拉列表通過ajax調用動態填充。 即。 從下拉列表中選擇一個值會觸發ajax調用並動態填充所有下拉框。

此表單具有發布和調出另一個表單的按鈕。 我遇到的問題是,當控制器中發生異常時,如何向用戶顯示錯誤消息並保留用戶填寫的表單值?

這是我的看法:

<div class="col-lg-6">
<div class="panel panel-default animated zoomInDown" style="padding-top:25px">
    <div class="fa fa-spinner fa-spin" id="dashSpinner" style="display:none;text-align:center;"></div>
    @using (Html.BeginForm("Create", "MyEntities", FormMethod.Post, new { id = "createEntityForm" }))
    {
       /*Form consists of dropdowns and text boxes*/
    }
</div>

這是我的控制器:

        [HttpPost]
    public ActionResult Create([Bind(Include = Entities)]  EntityModel model)
    {
        try
        {
                //If everything goes well, redirect to another form
                return RedirectToAction("AnotherForm", "Event", new { id = eventid });
            }
        }
        catch (Exception e)
        {
            //Catch exception and show it to the user?
            log.Error(e);
            model.Error = e.Message;
        }

        return View(model);
    }

這是我的ajax調用,向用戶顯示錯誤消息

    $("#createEntityForm").on("submit", function (e) {
        $("#dashSpinner").show();
        debugger;
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            //success: function (response) {
            //    debugger;
            //},
            error: function (response) {
                debugger;

                $("#dashSpinner").hide();
                swal({
                    title: "Error",
                    text: "You cannot take this type of action on this event.",
                    type: "error",
                    showConfirmButton: true
                });
            }                
        });


        $("#dashSpinner").hide();
    });

服務器響應的狀態碼不同於200時,將執行jQuery.ajax錯誤回調。

您應該使用HttpStatusCodeResultmsdn )或在catch塊中設置Response.StatusCodemsdn )返回響應。

觸發Error事件的是獲取非2xx狀態代碼。

更改您的ActionMethod以使用非2xx狀態代碼。 您可以使用Response.StatusCode = 500;

您還總是返回一個視圖-如果只想顯示一條錯誤消息,則返回JsonResult然后更新錯誤處理以僅顯示此錯誤可能會更容易。 在這種情況下,您的ActionMethod catch語句可能變為:

catch (Exception e)
{
  log.Error(e);
  Response.StatusCode = 500;
  Response.TrySkipIisCustomErrors = true;
  return Json(new { message = e.Message } );
}

然后,您需要更新JQuery錯誤處理程序以顯示該消息,因為當前該消息將始終顯示相同的錯誤(“您無法對此事件執行此類操作。”)。 為此,您需要輸出作為JSON負載的一部分發送的消息。

error: function (response) {
    $("#dashSpinner").hide();
    swal({
        title: "Error",
        text: response.responseJSON.message,
        type: "error",
        showConfirmButton: true
    });
}   

在管制員處

     [HttpPost]
    public ActionResult Create([Bind(Include = Entities)]  EntityModel model)
    {
      //If something goes wrong return to the form with the errors.

      if(!ModelState.isValid()) return Create(model);


       //If everything goes well, redirect to another form
         return RedirectToAction("AnotherForm", "Event", new { id = 


      return View(model);
    }

您可以在客戶端對jquery進行檢查,以確保其兼容性。 https://exceptionnotfound.net/asp-net-mvc-demystified-unobtrusive-validation/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM