How do you create conditionally necessary properties with an MVC 3 card that will work with client-side validation, as well as server-side validation when disabling JS? For instance:
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:
Name and Age are required if Location not specified.Location is required only if Name and Age not set.- It doesn’t matter if the name, age and location are set.
In the view, I need the result sent to Action if the name / age is given. And a different Action value if set to "Location". I tried with two separate forms with different Get Url's; this works fine except that validation rules cause problems. Preferably, I would like to use 2 separate Get action Url, 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 a location is provided, verification will not be performed as PersonModel expects the name and age to be set as well. And vice versa with name / age.
Based on the above example, how do you create conditionally necessary properties with an MVC 3 framework that will work with client-side validation, as well as server-side validation when disabling JS?
source share