Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 - complex model, properties have same field name, unable to render model

I need help in rendering a complex model.

I have a complex model with 2 class properties. All 3 classes (AddProjectQnrModel, ProjectModel, QTModel) have GroupId and GroupName properties.

public class AddProjectQnrModel
    {
        [Required]
        public int GroupId { get; set; }

        public string GroupName { get; set; }

        public ProjectModel Project { get; set; }

        public QCTModel QCT { get; set; }
    }

In the view I am using editor templates :

@Html.EditorFor(x => x.Project, "_EditProject.cshtml")
@Html.EditorFor(x => x.QCT, "_QCT-v1.cshtml")

I cannot use @html.Partial as it will not bind the properties correctly, so I have to use editor templates.

On running the project I get this error:

Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: required

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: required

Source Error: 

Line 26: 
Line 27:         @Html.EditorFor(x => x.Project, "_EditProject.cshtml")
Line 28: 
Line 29:         
like image 548
user1058895 Avatar asked Nov 23 '11 19:11

user1058895


1 Answers

I think you've run into something similar to this issue.

MVC will automatically add a Required validation for GroupId because int is not a nullable type. When you add an explicit specification of [Required], the validation is duplicated and results in your error. Remove the explicit [Required] attribute for any properties that are inherently not nullable and things should work as you expect.

Alternatively, if you want to prevent the automatic generation in favor of the explicit [Required] declarations, you can add the following to Application_Start as seen on this previous answer:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false
like image 105
David Ruttka Avatar answered Sep 27 '22 16:09

David Ruttka