asp.net-mvc 如何从剃刀视图内部检查我的模型是否有效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8599639/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:38:59  来源:igfitidea点击:

How can I check if my model is valid from inside the razor view?

asp.net-mvcasp.net-mvc-3razor

提问by Samantha J T Star

I need to do a check if my model is valid from inside my Razor view. If it's valid then I want to be able to show some HTML.

我需要从 Razor 视图中检查我的模型是否有效。如果它有效,那么我希望能够显示一些 HTML。

How can I do this. I want something like

我怎样才能做到这一点。我想要类似的东西

@if ( Model.IsValid ) {

}

but the above does not work

但以上不起作用

回答by Phil Klein

You can check whether or not the ModelState is valid, but keep in mind that you're only checking the validity of the ModelState at the time the web request was made:

您可以检查 ModelState 是否有效,但请记住,您只是在发出 Web 请求时检查 ModelState 的有效性:

@if (ViewData.ModelState.IsValid) {
    ...
}

Additionally, you can check validatity of a property on the model in the view:

此外,您可以在视图中检查模型上属性的有效性:

@if (ViewData.ModelState.IsValidField("FIELD_NAME")) {
    ...
}