Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState is marked invalid for an empty non-required field

A bit of a mystery. I have a viewmodel with a Year property:

public class TradeSpendingSalesViewModel
{       
    public string ProductCode { get; set; }
    public IEnumerable<SelectListItem> AllowTypeSelect { get; set; }
    public string AllowType { get; set; }
    public IEnumerable<SelectListItem> YearsSelect { get; set; }
    public int Year { get; set; }
}

If I post an empty viewmodel to my controller:

[HttpPost]
public ActionResult Index(TradeSpendingSalesViewModel vm)
{
    var allErrors = ModelState.Values.SelectMany(v => v.Errors);
    foreach (var e in allErrors)
    {
        Response.Write(e.ErrorMessage);
    }
}

Then I get a single error with a message of: "The Year field is required."

Since I haven't annotated the viewmodel Year field with the Required attribute, I'm unclear why this error is being generated.

Any ideas?

like image 944
Mister Epic Avatar asked Mar 26 '13 17:03

Mister Epic


1 Answers

ValueTypes by default are implicitly marked as Required in mvc. This was done for purpose, actually, because they by definition are non-nullable.

I would suggest you to set Year as int?, otherwise, if it's not correct in your case, you may change to false

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes

in Global.asax.cs.

like image 145
Dima Avatar answered Oct 14 '22 13:10

Dima