c# - How to make an extension method on an enumeration type still applicable even though the enum object is null? -


scenario:

the create action method pass uninitialized instance of person view. view show dropdown control "--select--" highlighted. since property sex nullable, cannot invoke extension method.

how fix 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 selectlist,"--select--") </div> 

extension:

 public static class utilities     {         public static selectlist getselectlist<tenum>(this tenum obj)         {             var values = tenum x in enum.getvalues(typeof(tenum))                          select new { text = x.tostring(), value = x };             return new selectlist(values, "value", "text", obj);         }     } 

why don't make extension method accept nullable parameter? (this extension method looks code smell me)

public static class utilities {     public static object getselectlist<tenum>(this tenum? obj)         tenum : struct      {         var values = 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(); 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -