Mikayil Abdullayev
Mikayil Abdullayev

Reputation: 12366

Do I have to have 2 fields for one property in order to fill a dropdownlist?

My view is strongly typed to the following model:

 public class CitizenDocument{
    public string Name{get;set;}
    public SocialStatus SocialStat{get;set;}
    public AppType ApplicationType{get;set;}
    public int Age{get;set;}
    public ReplyMethod PreferredReplyMethod{get;set;}
    .......//omitted for brevity
 }

Here are the three custom types I used above

  public Enum SocialStatus{
    Servant=1,Worker,Peasent,Student,Unemployed,Pensioner
  }

  public Enum AppType{
    Appliation=1,Complaint,Proposal,Query
  }

  public Enum ReplyMethod{
    Letter=1,Verbal
  }

Of course I'll need dropdownlists to present them in the view. The DropDownListFor<> method needs at least two things- one for storing the selected option value, the other one is the SelectList to populate the dropdownlist from. I don't want to pass the SelectList through ViewBag, which means the only way remaining is passing it inside the model. But this way I'll have to have a separate SelectList for all of the above three properties. Am I right? Or is there any other way that I'm not aware of? I've read lots of SO post regarding this but almost everyone recommends going model way as if there will always be one property of a model.

Upvotes: 0

Views: 53

Answers (1)

Vladyslav  Kurkotov
Vladyslav Kurkotov

Reputation: 505

@{
        var dictionary =  Enum.GetValues(typeof(SocialStatus)).Cast<SocialStatus>().ToDictionary(item => (int)item, item => item.ToLocalizedString());
        var selectList = new SelectList(dictionary, "Key", "Value", Model.SubscriptionTypeId);
    }
@Html.DropDownListFor(m => m.SocialStatusId, selectList)

So just store id of selected enum in model. P.S.: ToLocalizedString() is our custom method for getting the name of enum item

Upvotes: 1

Related Questions