May 25, 2012 06:47 by
Scott
This blog post shows how to validate models containing complex types such as Objects and Lists in ASP.NET MVC 3.
In a first step we modify the properties of the model ( Models/ValidationModel.cs) and add some complex types:
public class ValidUserNameAttribue : ValidationAttribute
{
public override bool IsValid(object value)
{
return (value != null && value.ToString() == "Bob");
}
}
public class User
{
[Required]
[StringLength(8, MinimumLength = 3)]
[ValidUserNameAttribue(ErrorMessage = "User name != 'Bob'")]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(8, MinimumLength = 3)]
[Display(Name = "Display name")]
public string DisplayName { get; set; }
}
public class ValidationModel
{
public User User { get; set; }
public List Users { get; set; }
}
In a second step we modify the form ( Views\Home\Partial\_Form.cshtml) to add input element for the new model properties:
@model MVC3_Ajax_Form_jQuery_Validation.Models.ValidationModel
@DateTime.Now: Partial/_Form.cshtml rendered
< hr/>
@using (Html.BeginForm("Form", "Home"))
{
<h1><em>User</em> object</h1>
<p>
@Html.LabelFor(m => m.User.UserName):
@Html.EditorFor(m => m.User.UserName)
@Html.ValidationMessageFor(m => m.User.UserName)
</p>
<p>
@Html.LabelFor(m => m.User.DisplayName):
@Html.EditorFor(m => m.User.DisplayName)
@Html.ValidationMessageFor(m => m.User.DisplayName)
</p>
<h1>List of <em>User</em> objects</h1>
for (var i = 0; i <= 1; i++)
{
<h2>User @i</h2>
<p>
@Html.LabelFor(m => m.Users[i].UserName):
@Html.EditorFor(m => m.Users[i].UserName)
@Html.ValidationMessageFor(m => m.Users[i].UserName)
</p>
<p>
@Html.LabelFor(m => m.Users[i].DisplayName):
@Html.EditorFor(m => m.Users[i].DisplayName)
@Html.ValidationMessageFor(m => m.Users[i].DisplayName)
</p>
}
<input type="submit" value="Submit" />
}
In a last step we adapt the “success-view” ( Views\Home\Partial\_Success.cshtml) that is shown after the data have been successfully validated on the server side:
@model MVC3_Ajax_Form_jQuery_Validation.Models.ValidationModel
< p><strong>Model is valid :)</strong></p>
< p>
Model.User.Username: '@Model.User.UserName'<br />
Model.User.DisplayName: '@Model.User.DisplayName'<br />
Model.Users[0].Username: '@Model.Users[0].UserName'<br />
Model.Users[0].DisplayName: '@Model.Users[0].DisplayName'<br />
Model.Users[1].Username: '@Model.Users[1].UserName'<br />
Model.Users[1].DisplayName: '@Model.Users[1].DisplayName'
</ p>
As you can see in the source code above, there is no magic; model binding and validation of complex objects and lists work out of the box in ASP.NET MVC 3.