DropDownListFor() bindling value AND text to viewm

2019-08-25 06:33发布

I have a form on a View with a dropdown list, implemented with DropDownListFor(). This View is strongly typed to a ViewModel, which has a SelectList property to hold the options of the dropdown, and then another property to hold the selected value of the dropdown. This is working fine, but what I'd like to do is, hold both the selected value AND selected text of the dropdown in my second property. The reason I want to do this is so that as the form selfposts, I have both the text and value of each selection.

I tried changing the selected value property from an int to a KeyValuePair but only the int part of the pair is set on form submission.

Perhaps there is a better way altogether to accomplish this, I am open to all suggestions including a partial redesign of my methods.

Controller (building SelectList)

SelectList leadTypeGroups = new SelectList(_enrollmentRepository.GetLeadTypeGroups(), "Key", "Value");

ViewModel

public KeyValuePair<int, string> LeadTypeGroupID { get; set; }
public SelectList LeadTypeGroups { get; set; }

View

@Html.DropDownListFor(selected => Model.LeadTypeGroupID, Model.LeadTypeGroups, " ")

2条回答
疯言疯语
2楼-- · 2019-08-25 06:49

Change the ViewModel to a List and then use a for loop to spit out a drop down for each item in the list. Something like...

View

@for( int i = 0; i < Model.LeadTypeGroupIDs; i++ )
{
  @Html.DropDownListFor(x => Model.LeadTypeGroupIDs[i], Model.LeadTypeGroups, " ")
}

ViewModel

public List<string> LeadTypeGroupIDs { get; set; }
public SelectList LeadTypeGroups { get; set; }
查看更多
叛逆
3楼-- · 2019-08-25 06:54

Have the sever pull the values from the database (or an in-memory cache) on each request. Alternatively, have a hidden field with javascript that updates it with the appropriate text whenever the dropdown selection changes.

查看更多
登录 后发表回答