簡體   English   中英

如果Controller失敗,如何在View中顯示錯誤? ASP.NET MVC

[英]How to show error in View if the Controller fails ? ASP.NET MVC

服務器端,我有一個返回JsonResult的事務:

public JsonResult DoStuff(Guid id, string userInputText)
{
     var product = _repository.Product(id); //busines logic

     //Only a specific product must have userInputText <= 10 characters. 
     //Other products may have as many characters as the user wants.
     if(product == Enum.SpecificProduct && userInputText.Count() > 10)
     {
          //The user input text comes from the View...
          //If it has more then 10 characters, need to send the errorMessage to the View.
          return Json(new { success = false, errorMessage = "error message" }, JsonRequestBehavior.AllowGet);
     }

     //Otherwise, do stuff on the product... 

     //and return success at the end.
     return Json(new { success = true });
}

另一方面,在客戶端我有這個:

using (Ajax.BeginForm("DoStuff", ajaxOptions))
{
    <span>Enter the text:</span>
    @Html.TextArea("userInputText", new { onkeyup = "SyncContents(); return false;" })

    <input type="submit" value="Add" />
    <!-- error message should be displayed here-->
}

這是AjaxOptions:

var ajaxOptions= new AjaxOptions
{
    OnSuccess = "reload",
    OnFailure = "FailMessage"
};

如果輸入的文本超過10個字符,當按下“添加”按鈕時,控制器正在服務器端執行代碼並失敗,如何從那里獲取errorMessage並在此處使用它,在視圖中,告知用戶?

我試着提醒一條消息:

<script>
    function FailMessage() {
        alert("Fail Post");
    }
</script>

但是沒有彈出“失敗的帖子”出現。

最好的祝福。

這里的問題是Ajax幫助器認為你的所有響應都是成功的。 您的控制器操作正在返回HTTP 200,因此沒有問題。

https://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.onfailure(v=vs.118).aspx#P:System.Web.Mvc.Ajax.AjaxOptions.OnFailure

AjaxOptions.OnFailure屬性

如果響應狀態不在200范圍內,則調用此函數。

因此,您需要使用成功處理程序並顯式檢查JSON success參數。

或者讓您的操作更改響應的HttpStatusCode。

if (notValid)
{
    Response.StatusCode = 400;  // Bad Request
    return Json(new { success = false, errorMessage = "error message" }, JsonRequestBehavior.AllowGet);
}

但是對於驗證錯誤,我只是檢查成功處理程序中的錯誤。

是的,您應該在客戶端和服務器上進行驗證。

暫無
暫無

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

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