gpt4 book ai didi

asp.net - 删除 ASP.NET MVC 中的 ModelState 错误

转载 作者:行者123 更新时间:2023-12-04 01:55:54 38 4
gpt4 key购买 nike

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

我看到这篇文章 Is there a strongly-named way to remove ModelState errors in ASP.NET MVC

建议使用 ModelBindingHelper.ClearValidationStateForModel(Type, ModelStateDictionary, IModelMetadataProvider, string)。

但我无法找到任何进一步的帮助。

谁能建议一个使用 ClearValidationStateForModel 删除模型属性的工作示例?

最佳答案

这应该会删除 CreatePost View 模型的 Title 属性的验证错误。

[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 希望根据另一个属性值排除某个要验证的属性。这应该可以正常工作。

[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 - 删除 ASP.NET MVC 中的 ModelState 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361095/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com