How do you create conditionally required properties with the MVC 3 framework that will work with Client Side Validation as well as Server Side Validation when JS is disabled? For example:
public class PersonModel
{
[Required] // Requried if Location is not set
public string Name {get; set;}
[Range( 1, 5 )] // Requried if Location is not set
public int Age {get; set;}
[Required] // Only required if Name and Age are not set.
public string Location {get; set;}
}
The rules in this example are:
Name
andAge
are required ifLocation
is not set.Location
is required only ifName
andAge
are not set.- Doesn't matter if Name, Age and Location are all set.
In the View, I need the result sent to an Action
if Name/Age are set. And a different Action
if Location is set. I've tried with 2 separate forms with different Get Url's; this works great except the validation rules are causing problems. Preferrably, I would like the use of 2 separate Get action Url's, i.e.,
@model PersonModel
@using( Html.BeginForm( "Age", "Person", FormMethod.Post ) )
{
@Html.TextBoxFor( x => x.Name )
@Html.ValidationMessageFor( x => x.Name )
@Html.TextBoxFor( x => x.Age )
@Html.ValidationMessageFor( x => x.Age )
<input type="submit" value="Submit by Age" />
}
@using( Html.BeginForm( "Location", "Person", FormMethod.Post ) )
{
@Html.TextBoxFor( x => x.Location )
@Html.ValidationMessageFor( x => x.Location )
<input type="submit" value="Submit by Location" />
}
Based on the PersonModel
above, if the Location is submitted, the validation will fail since the PersonModel is expecting the Name and Age to be set as well. And vice versa with Name/Age.
Given the above mocked up example, how do you create conditionally required properties with the MVC 3 framework that will work with Client Side Validation as well as Server Side Validation when JS is disabled?