【发布时间】:2017-09-13 15:35:27
【问题描述】:
在服务器端我有一个返回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>
但没有弹出“发帖失败”。
最好的问候。
【问题讨论】:
-
我不确定您的 ajaxOptions 是如何与上述代码中的 saveOptions 连接的。也许将您的 ajaxOptions 更改为新的 Ajaxoptions { OnSuccess = "reload", OnFailure = "FailMessage" },并记得在 "reload" 后添加一个 ","
-
真的很抱歉这些错误,我刚刚编辑了我的问题。 saveOptions 实际上是 ajaxOption,我在处理错误的名称。谢谢。
-
因此,用户在文本区域中最多只能输入 10 个字母。如果用户输入了 11 个或更多字符。那么您想要错误消息吗?
-
@T_Roy 是的,这正是我所需要的。
-
您是否有理由在服务器端进行检查?这可以通过客户端验证来完成
标签: javascript html asp.net-mvc html-helper