javascript – 如果Controller失败,如何在View中显示错误? ASP.NET MVC
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 如果Controller失败,如何在View中显示错误? ASP.NET MVC,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1994字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 如果Controller失败,如何在View中显示错误? ASP.NET MVC](/upload/InfoBanner/zyjiaocheng/782/cfbcc77f3be444ea8186a5daf86a5616.jpg)
在服务器端,我有一个返回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,因此没有问题.
AjaxOptions.OnFailure属性
This function is called if the response status is not in the 200 range.
因此,您需要使用成功处理程序并显式检查JSON成功参数.
或者让您的操作更改响应的HttpStatusCode.
if (notValid)
{
Response.StatusCode = 400; // Bad Request
return Json(new { success = false, errorMessage = "error message" }, JsonRequestBehavior.AllowGet);
}
但是对于验证错误,我只是检查成功处理程序中的错误.
是的,您应该在客户端和服务器上进行验证.
内容总结
以上是互联网集市为您收集整理的javascript – 如果Controller失败,如何在View中显示错误? ASP.NET MVC全部内容,希望文章能够帮你解决javascript – 如果Controller失败,如何在View中显示错误? ASP.NET MVC所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。