验证前ModelState.IsValid为false [英] ModelState.IsValid is false prior to validation
问题描述
我们编写了一个自定义模型联编程序,该联编程序覆盖了 ComplexTypeModelBinder
的 CreateModel
方法,因此我们可以拥有注入
到我们的 ViewModels
中,而不必通过注入的客户
和 repos
从控制器
进入我们的模型
。
We wrote a custom model binder that overrides the CreateModel
method of the ComplexTypeModelBinder
so that we can have injection
into our ViewModels
instead of having to pass the injected clients
and repos
to our model
from the controller
.
例如,对于模型
,例如:
public class ThingViewModel
{
public ThingViewModel (IThingRepo thingRepo) {}
}
在我们的控制器
中,我们可以执行以下操作:
In our controller
we can do:
public class ThingController : Controller
{
public IActionResult Index(ThingViewModel model) => View(model);
}
这很好用,这是<$ c $的替代部分c>自定义模型联编程序:
protected override object CreateModel(ModelBindingContext bindingContext)
{
var model = bindingContext.HttpContext.RequestServices.GetService(bindingContext.ModelType);
if (model == null)
model = base.CreateModel(bindingContext);
if (bindingContext.HttpContext.Request.Method == "GET")
{
bindingContext.ValidationState[model] = new ValidationStateEntry { SuppressValidation = true };
}
return model;
}
简单明了的东西。
问题在于,如果我们在 GET操作方法
中使用 ValidationSummary
在 view
,因为未运行 validation
,因此 ModelState.IsValid
为 false
,即使存在 0个错误
...这也会导致 ValidationSummary
以显示为空,并带有红色边框。一个烦人的解决方法是,先调用 ModelState.Clear()方法
,然后再将 model
发送到视图
。我可以以某种方式更改它,以便在验证$ c时将
IsValid
默认设置为 true
$ c>尚未运行?还是有更好的方法?
The problem, is that in our GET action methods
, if we use a ValidationSummary
in the view
, because validation
was not run, the ModelState.IsValid
is false
, even though there are 0 errors
... this causes the ValidationSummary
to show up empty with a red border around it. An annoying work-around for this is to call the ModelState.Clear() method
prior to sending the model
into the view
. Can I somehow change it so that IsValid
is defaulted to true
when validation
has not been run yet? Or is there a better way?
推荐答案
此问题与IoC模型绑定无关。 MVC存在一个问题,即使您没有验证错误,仍会为验证摘要呈现一个空容器。两种可能的解决方法包括:
This issue is not related to IoC model binding. MVC has an issue of still rendering an empty container for your validation summary, even if you have no validation errors. Two possible work arounds include:
- 创建一个包装验证摘要的局部文件。在那一部分中,在呈现验证摘要之前检查模型状态中是否存在任何错误。使用该部分代替原来的验证摘要。
- 添加一些CSS,如果不包含任何填充或可见列表项,则该CSS隐藏包含div的内容。如果没有可见的错误列表项,则容器的显示应该为空。
有关其他信息,请参见以下内容:相关问题
See this for additional info: Related Question
这篇关于验证前ModelState.IsValid为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!