When adding news ModelState.IsValid always false .

Model :

 public class NewsViewModelItem { [Key] public int Id { get; set; } [Required] [Display(Name = "Short Title")] public string ShortTitle { get; set; } [Required] [Display(Name = "Full Title")] public string FullTitle { get; set; } [Required] [Display(Name = "Short Article")] public string ShortArticle { get; set; } [Required] [Display(Name = "Full Article")] public string FullArticle { get; set; } [Required] public virtual List<NewsImageModelItem> NewsImages { get; set; } } 

Throws an error due to NewsImages .

System.Web.HttpPostedFileWrapper 'to type' Schedule.BLL.Model.NewsImageModelItem 'parameter.

I would like to understand how to skip NewsImages in Data annotation , or somehow solve this problem differently.

  • And what do you mean when you write [Required] public virtual List<NewsImageModelItem> NewsImages { get; set; } [Required] public virtual List<NewsImageModelItem> NewsImages { get; set; } [Required] public virtual List<NewsImageModelItem> NewsImages { get; set; } - collection required? Well, you write the type public virtual List<NewsImageModelItem> NewsImages { get; } = new List<NewsImageModelItem>() public virtual List<NewsImageModelItem> NewsImages { get; } = new List<NewsImageModelItem>() , the attribute is not needed here - Andrey NOP

1 answer 1

Create your own attribute from ValidationAttribute and override the behavior for IsValid (its own logic for your NewsImageModelItem collection)
https://msdn.microsoft.com/ru-ru/library/cc679289(v=vs.110).aspx

and then you can change your property

 [MyRequired] public virtual List<NewsImageModelItem> NewsImages { get; set; } 

Your code will be something like this:

 using System.ComponentModel.DataAnnotations; public class MyRequiredAttribute : ValidationAttribute { public override bool IsValid(object value) { bool result; var collection = (List<NewsImageModelItem>)value; if (collection == null || collection.Count == 0) { result = false; } else result = true; return result; } } 

If VS cannot find using System.ComponentModel.DataAnnotations; Add the link to this DLL to the project.

  • And if the collection is not List , and some other? Another attribute to do? - Andrey NOP
  • In vain edited because VS does not always offer to add the DLL itself to the project and you need to insert the link with your hands. for example, I have now been so. - Dev
  • You had duplication of the same information there, why? - Andrey NOP
  • var collection = (List <NewsImageModelItem>) value; If (collection == null) here you can recheck several parameters. - Dev