Step 1, Create a model to contain the list of values.
In this example the code is as follows:public class SalutationsList
{
public static IEnumerable<SelectListItem> GetSalutationsList()
{
IList<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem{Text = "", Value = ""},
new SelectListItem{Text = "Mr", Value = "Mr"},
new SelectListItem{Text = "Mrs", Value = "Mrs"},
new SelectListItem{Text = "Ms", Value = "Ms"},
new SelectListItem{Text = "Sir", Value = "Sir"},
new SelectListItem{Text = "Esq", Value = "Esq"},
new SelectListItem{Text = "Dr", Value = "Dr"}
};
return items;
}
}
The key point to note is that this class has a static method that returns IEnumerable<SelectListItem>. The method is static as it will not change for the life of the application, so there is no need for it to be instantiated each time it is used which will save a bit of CPU and memory - important for a busy site.
Step 2, Create the custom validation method.
For this example, you can use the following code:
public class SalutationsListValidateAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string theValue = ""; //the deafult is a empty string.
if (value != null)
{
theValue = value.ToString();
}
foreach (SelectListItem salutationValue in SalutationsList.GetSalutationsList())
{
if (salutationValue.Text.ToString() == theValue)
{
return ValidationResult.Success;
}
}
return new ValidationResult("The selected value is not in the list of accepted salutations.");
}
}
This will ensure that the model will validate against the list of values in the SalutationsList class. If the implementation of SalutationsList changes to dynamically read data from a data source, this validation code will still be valid.
Step 3, Add the salutation attribute to the model it is used with.
The code for this example is
[SalutationsListValidate]
public string Salutation { get; set; } //class SalutationList
Step 4, Add (Update) code to your views.
The code in your view will look something like:<div class="form-group">
@Html.LabelFor(model => model.Salutation, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(x => Model.Salutation, ToyLibrary.Models.SalutationsList.GetSalutationsList(), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Salutation, "", new { @class = "text-danger" })
</div>
</div>
Summary.
By using this approach, the validation will be applied on client and server side. This is handy, if someone tries to over post, then the field will be validated. Also, this will validate any updates you try to do as part of database initialization using entity framework. That said, you will be serving up some unobtrusive java script to validate on the client side which may be a consideration.
No comments:
Post a Comment