删除ASP.NET MVC中的ModelState错误 [英] Remove ModelState errors in ASP.NET MVC

查看:80
本文介绍了删除ASP.NET MVC中的ModelState错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以删除ASP.Net MVC6中某个模型中某些属性的模型验证.

Is there any way to remove model validation for some properties in a Model in ASP.Net MVC6.

我碰到了这篇文章建议使用ModelBindingHelper.ClearValidationStateForModel(类型,ModelStateDictionary,IModelMetadataProvider,字符串).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆