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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With