javascript 如何知道 ModelState 是否包含错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8907630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How know if ModelState contains errors
提问by John x
When a form is posted in my controller, I make the following check:
在我的控制器中发布表单时,我会进行以下检查:
if(ModelState.IsValid)
If the model is not valid, errors are added to the ModelState
. The model is then passed to the view with validation summary.
如果模型无效,则会将错误添加到ModelState
. 然后将模型与验证摘要一起传递给视图。
However, I want to check if the ModelState
has errors from inside the jQuery ready
handler, so that I can add some additional behavior if the form has errors. Is that possible?
但是,我想检查ModelState
jQueryready
处理程序内部是否有错误,以便在表单有错误时添加一些额外的行为。那可能吗?
回答by Darin Dimitrov
You could spit global javascript variable:
你可以吐出全局 javascript 变量:
<script type="text/javascript">
var isValid = @Html.Raw(Json.Encode(ViewData.ModelState.IsValid));
</script>
and then:
接着:
$(function() {
if (!isValid) {
alert('opa');
}
});
回答by Amin Saqi
a little addition to @Dimitrov answer:
对@Dimitrov 回答的一点补充:
<script type="text/javascript">
var isValid = '@Html.Raw(Json.Encode(ViewData.ModelState.IsValid))';
if (isValid != 'true')
// model has some errors...
</script>
It's important to use single qoutes around the helper. Otherwise, that ending semicolon ;
cause problems. Nether you can write it, nor you can't, at all cases it cause a syntax error. Unless you put those single quotes around the helper as I mentioned.
在 helper 周围使用单个 qoutes 很重要。否则,结尾的分号;
会导致问题。你可以写它,也不能写,在任何情况下它都会导致语法错误。除非你像我提到的那样在帮助器周围加上那些单引号。
回答by raklos
In addition to Darins Answer:
除了达林斯回答:
In .cshtml:
在 .cshtml 中:
@Html.Hidden("IsValid", Json.Encode(ViewData.ModelState.IsValid))
in JS
在JS中
var isValid = $('#IsValid').val().toLowerCase() == "true";