来自 IEnumerable<ViewModel> 的 ASP MVC5 ModelState.Remove("myField")

问题描述

  • 我想从模型验证中删除一个必填字段,它是 包含在视图模型列表中。
  • 我需要拥有前端验证所需的所有字段,但在后端我需要从模型验证中删除 company

modelValues - 将只包含 idname

company - 我需要单独发送这个

$.ajax({
       ...,data: JSON.stringify({"vmData" : modelValues,"company": "Google"})
       ...
});

public class Userviewmodel{
    [required]
    public int id{get;set;}
    [required]
    public string name{get;set;}
    [required]
    public string company{get;set;}
}

public ActionResult Index(IEnumerable<Userviewmodel> vmData,string company){
   if(!string.IsNullOrEmpty(company)){
      ModelState.Remove("company");
   }
   
   // is never valid because "company" is always null
   if(ModelState.IsValid()){...}
}

我是否使用了错误ModelState.Remove("company");?它不适用于 IEnumerable?

解决方法

我已经设法通过这样做来解决它:

if(!string.IsNullorEmpty(company)){
 for(var i=0; i < vmData.Count; i++){
   ModelState.Remove("vmdata[" + i + "].company");
 }
}