How to make an extension method on an enumeration type still applicable even though the enum object is null?
Scenario:
The Create
action method will pass an uninitialized instance of Person
to the View
.
The View
will show a dropdown control with "--Select--" highlighted.
Since the property Sex
is nullable, I cannot invoke the extension method.
How to fix this problem?
Model:
namespace MvcApplication1.Models
{
public enum Sex { Male, Female };
pub开发者_运维知识库lic class Person
{
public int Id { get; set; }
public string Name { get; set; }
[Required(ErrorMessage="Please select either Female or Male.")]
public Sex? Sex { get; set; }
}
}
Controller:
public ActionResult Create()
{
var p = new Person();
ViewBag.SelectList = p.Sex.Value.GetSelectList();//Source of error!
return View(p);
}
Partial View:
@model MvcApplication1.Models.Person
@Html.HiddenFor(model => model.Id)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div>
@Html.DropDownListFor(model => model.Sex, ViewBag.SelectList as SelectList,"--Select--")
</div>
Extension:
public static class Utilities
{
public static SelectList GetSelectList<TEnum>(this TEnum obj)
{
var values = from TEnum x in Enum.GetValues(typeof(TEnum))
select new { Text = x.ToString(), Value = x };
return new SelectList(values, "Value", "Text", obj);
}
}
Why don't you make your extension method to accept a Nullable
as a parameter? (This extension method looks like a code smell to me)
public static class Utilities
{
public static object GetSelectList<TEnum>(this TEnum? obj)
where TEnum : struct
{
var values = from TEnum x in Enum.GetValues(typeof(TEnum))
select new { Text = x.ToString(), Value = x };
return new SelectList(values, "Value", "Text", obj);
}
}
and use without extracting value:
ViewBag.SelectList = p.Sex.GetSelectList();
精彩评论