Frage

It is the first I have been using the asp.net mvc webApi, and I have Post/Put methods that has a parameter called ProductViewModel. Some properties of this ViewModel has data annotations to validate such as Required, StringLenght etc... I have the post method like this:

public HttpResponseMessage Post([FromBody] ProductViewModel value)
{
   if (ModelState.IsValid)
   {
      // persist data here...

      return Request.CreateResponse(HttpStatusCode.OK);
   }

   return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
}

I have the GetErrors() method as an extension to get an List<> of my errors and pass to the client. My question is: Why the ModelState does not work?

if I pass null into a property of my ViewModel this validation simply does not work. IsValid property is always true. Is there any way to work around this and get the ModelState work such as MVC ?

My Model looks like this:

public class ProductViewModel
{
    [Display(ResourceType = typeof(Resources.Global), Name = "Name")]
    [Required(ErrorMessageResourceType = typeof(Resources.Global), ErrorMessageResourceName = "Required")]
    [StringLength(100, ErrorMessageResourceType = typeof(Resources.Global), ErrorMessageResourceName = "Range")]
    public string Name { get; set; }

    [Display(ResourceType = typeof(Resources.Global), Name = "ShortName")]
    [Required(ErrorMessageResourceType = typeof(Resources.Global), ErrorMessageResourceName = "Required")]
    [StringLength(20, ErrorMessageResourceType = typeof(Resources.Global), ErrorMessageResourceName = "Range")]
    public string ShortName { get; set; }
}

Thank you.

War es hilfreich?

Lösung

Could you make sure that you are passing in the Content-Type as part of your request? (if content-type is not passed, a default value for the particular type is set and the model state would not be having errors...this bug has been fixed recently).

also, you could do the following:

return Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top