【问题标题】:ASP MVC5 ModelState.Remove("myField") from IEnumerable<ViewModel>来自 IEnumerable<ViewModel> 的 ASP MVC5 ModelState.Remove("myField")
【发布时间】:2021-05-25 19:00:26
【问题描述】:
  • 我想从模型验证中删除一个必填字段,该字段是 包含在 viewModel 列表中。
  • 我需要前端验证所需的所有字段,但在后端我需要从模型验证中删除 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?

【问题讨论】:

    标签: validation asp.net-mvc-5 modelstate


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多