Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mvc4 RTM validation throwing an error

Has something changed with the rtm bits regarding the validation of models.

I have a simple viewmodel that looks like

    public class ProductViewModel
    { 
    [Required]
    [DataMember(IsRequired = true)]
    public int ProductTypeId { get; set; }
    public string Product { get; set; }
    }

(I just added the DataMember(IsRequired = true) as the error message I get says to use it to fix the problem. However no joy)

Within my controller the model state is telling me model is valid however when I try passing the model to my api using RestSharp I get the following error.

{"Message":"An error has occurred.","ExceptionMessage":"Property 'ProductTypeId' on type 'Mine.Model.Model' is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(IsRequired=true)].","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Validation.Validators.ErrorModelValidator.Validate(ModelMetadata metadata, Object container)\r\n at System.Web.Http.Validation.DefaultBodyModelValidator.ShallowValidate(ModelMetadata metadata, ValidationContext validationContext, Object container)\r\n at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateNodeAndChildren(ModelMetadata metadata, ValidationContext validationContext, Object container)\r\n at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateProperties(ModelMetadata metadata, ValidationContext validationContext)\r\n at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateNodeAndChildren(ModelMetadata metadata, ValidationContext validationContext, Object container)\r\n at System.Web.Http.Validation.DefaultBodyModelValidator.Validate(Object model, Type type, ModelMetadataProvider metadataProvider, HttpActionContext actionContext, String keyPrefix)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.<>c_DisplayClass1.b_0(Object model)\r\n at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass361.<>c__DisplayClass38.<Then>b__35()\r\n at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass49.<ToAsyncVoidTask>b__48()\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func1 func, CancellationToken cancellationToken)"}

I wasnt having this problem with the rc bits but then I have only started to use the restsharp libary with the rtm bits.

Any help would be great.

like image 702
Diver Dan Avatar asked Oct 23 '22 11:10

Diver Dan


1 Answers

In addition to adding [DataMember(IsRequired = true)] to the property, you'll also need to ensure that the attribute [DataContract] is applied at the class level.

like image 51
ShadowChaser Avatar answered Oct 26 '22 21:10

ShadowChaser