删除ASP.NET MVC中的ModelState错误 [英] Remove ModelState errors in ASP.NET MVC
问题描述
有什么方法可以删除ASP.Net MVC6中某个模型中某些属性的模型验证.
Is there any way to remove model validation for some properties in a Model in ASP.Net MVC6.
which suggests using, ModelBindingHelper.ClearValidationStateForModel(Type, ModelStateDictionary, IModelMetadataProvider, string).
但是我无法在此找到任何进一步的帮助.
But I am unable to find any further help on this.
任何人都可以提出一个使用ClearValidationStateForModel删除模型属性的工作示例吗?
Can anyone please suggest a working example of removing a model property using ClearValidationStateForModel?
推荐答案
这应该删除CreatePost
视图模型的Title
属性的验证错误.
This should remove the validation errors for the Title
property of your CreatePost
view model.
[HttpPost]
public ActionResult Create(CreatePost model)
{
if (ModelState.IsValid)
{
//to do : Save and return something
}
ModelBindingHelper.ClearValidationStateForModel(model.GetType(),
ModelState,MetadataProvider,"Title");
return View(model);
}
此外,ModelState.ClearValidationState
也将起作用.
ModelState.ClearValidationState("Title");
根据评论,OP希望基于另一个属性值排除要验证的某个属性.这应该工作正常.
EDIT : As per the comment, OP wants to exclude a certain property to be validated based on another property value. This should work fine.
[HttpPost]
public ActionResult Create(CreatePost model) //CreatePost model
{
if (model.Type == 1)
{
ModelBindingHelper.ClearValidationStateForModel(model.GetType(),
ModelState, MetadataProvider, "Title");
}
if (ModelState.IsValid)
{
// to do : Do useful stuff and return something
}
return View(model);
}
这篇关于删除ASP.NET MVC中的ModelState错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!