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 };
public 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
Nullableas a parameter? (This extension method looks like a code smell to me)and use without extracting value: