Let’s say you have an enum like this:
public enum ColorsEnum
{
Undefined,
Blue,
Red,
Green
}
And a model like this:
public class Foo
{
public ColorsEnum PreferedColor { get; set; }
}
With a view like this:
@model WebUI.Models.Foo
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.PreferedColor)
@Html.DropDownListForEnum(m => m.PreferedColor)
<input type="submit">
}
Here is the helper for the DropdownListForEnum:
public static IHtmlString DropDownListForEnum<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
if (metaData.ModelType.IsEnum)
{
var names = Enum.GetNames(metaData.ModelType);
var translatedNames = GetTranslatedNames(metaData.ModelType);
var query = from p in names
select new SelectListItem
{
Text = translatedNames.ContainsKey(p) ? translatedNames[p] : p,
Value = p,
Selected = false
};
return htmlHelper.DropDownList(metaData.PropertyName, query.ToList());
}
else
{
throw new ApplicationException(
"The DropDownListForEnum helper function must be used with an enum property");
}
}
My question: how do you perform validation (client & server side) to be sure a valid color is choosed by the user? ‘Undefined’ color should be refused by the validation process.
Thanks.
I would use a nullable enum and a Required attribute on the view model:
So you could remove the
Undefinedvalue from your enum definition:and then slightly modify your helper:
and then have a simple controller to test:
and a corresponding view: