javascript - 如果 Controller 失败,如何在 View 中显示错误? ASP.NET MVC

标签 javascript html asp.net-mvc html-helper

服务器端,我有一个返回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 个字符,当按下“添加”按钮时, Controller 正在服务器端 上执行代码并失败,我如何获得错误消息从那里并在此处,在 View 中使用它来通知用户?

我试图提醒一条消息:

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

但是没有弹出“发布失败”。

最好的问候。

最佳答案

这里的问题是 Ajax 助手认为您的所有响应都是成功的。您的 Controller 操作正在返回 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 属性

This function is called if the response status is not in the 200 range.

因此您需要使用成功处理程序并显式检查 JSON success 参数。

或者让您的操作更改响应的 HttpStatusCode。

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

但是对于这里的验证错误,我只是检查成功处理程序中的错误。

是的,您应该在客户端和服务器上进行验证。

关于javascript - 如果 Controller 失败,如何在 View 中显示错误? ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46201574/

相关文章:

javascript - 如何设置 mobiscroll 的 maxDate?

javascript - 如何禁止用户从当前时间选择 future 时间?

javascript - typescript : logic to covert string array into custom object

javascript - jquery ui draggable 自动改变宽度

asp.net-mvc - 程序集使用 System.Web.Http 5.1,它的版本高于引用的程序集 System.Web.Http 5.0

c# - ASP.NET MVC 上传文件

javascript - 使用 PWA 构建应用程序

javascript - 动态地将一个 HTML 文件插入到另一个文件中?

javascript - 内容的历史可编辑的替代品

c# - 使用 C# 连接 RabbitMQ