Dropdownlist for with Dictionary is not wo

2019-04-24 14:07发布

问题:

I am trying to bind a dropdown in MVC3 in this way.

Model

public static Dictionary<string, string> SexPreference()
{
      var dict = new Dictionary<string, string>();
      dict.Add("Straight", "S");
      dict.Add("Gay", "G");
      dict.Add("Bisexual", "BISEX");
      dict.Add("Bicurious", "BICUR");
      return dict;
}

Controller

ViewBag.SexPreference = MemberHandler.SexPreference();

View

@{
var itemsSexPreference = new SelectList(ViewBag.SexPreference, "Value", "Key", Model.sexpreference);
}

@Html.DropDownListFor(m => m.sexpreference, @itemsSexPreference)

Dropdown is not selecting the selected value, don't know why.

回答1:

Why are you setting ViewBag.SexPreference when you have a model? Forget about this ViewBag. Also you should have 2 properties in order to make a dropdown list: a scalar type property to hold the selected value and a collection property to hold the list of selected values. Right now you seem to be using only one and attempting to bind the DropDown to a collection property which obviously doesn't make any sense.

Do it the right way, by using a view model:

public class MyViewModel
{
    public string SelectedSexPreference { get; set; }
    public Dictionary<string, string> SexPreferences { get; set; }
}

that you would populate in your controller action and pass to the view:

public ActionResult SomeAction()
{
    var model = new MyViewModel();

    // Set the value that you want to be preselected
    model.SelectedSexPreference = "S";

    // bind the available values
    model.SexPreferences = MemberHandler.SexPreference();

    return View(model);
}

and inside your view:

@model MyViewModel

@Html.DropDownListFor(
    m => m.SelectedSexPreference, 
    new SelectList(Model.SexPreferences, "Value", "Key")
)


回答2:

Model.sexpreference must be one of these values: Straight... This will Work:

public static Dictionary<string, string> SexPreference()
{
  var dict = new Dictionary<string, string>();
  dict.Add("S", "Straight");
  dict.Add("G", "Gay");
  dict.Add("BISEX", "Bisexual");
  dict.Add("BICUR", "Bicurious");
  return dict;
}

@{
    var itemsSexPreference = new SelectList(ViewBag.SexPreference, "Key", "Value", "S");
}


回答3:

I did it differently. It's very frustrating this whole thing.

In the controller do something like:

var percentagesFromDb = _service1.GetPercentagesFromDb(parameters);
var percentages = percentagesFromDb.ToDictionary(percentage => percentage.someKey, 
                                                percentage => percentage.someValue);
ViewData["selectedPercentages"] = percentages;

And then in the model:

[Display(Name = "%")]
public string Percentage { get; set; }

private static Dictionary<string, string> GetPercentageList()
{
    return new Dictionary<string, string>
    {
        {"100", "100%"},
        {"90", "90%"},
        {"80", "80%"},
        {"70", "70%"},
        {"60", "60%"},
        {"50", "50%"},
        {"40", "40%"},
        {"30", "30%"},
        {"20", "20%"},
        {"10", "10%"}
    };
}

public SelectList GetSelectList(string selected, object selectedPercentages)
{
    var selectedDict = new Dictionary<string, string>();
    if (selectedPercentages != null)
        selectedDict = (Dictionary < string, string>) selectedPercentages;
    var selectedvalue = selectedDict.ContainsKey(selected) ? selectedDict[selected] : "100";
    Percentage = selectedvalue;
    return new SelectList(GetPercentageList(), "Key", "Value");
}

And then finally in the view:

<table class="table table-bordered table-striped">
    <thead>
    <tr>
        <th>@Html.LabelFor(m => m.Items, new {@class = "control-label"})</th>
        <th>@Html.LabelFor(m => m.Percentage, new {@class = "control-label"})</th>
    </tr>
    </thead>
    <tbody>
    @foreach (var item in Model.Items)
    {
        <tr>
            <td>
                @item.Value
            </td>

            <td>
                @Html.DropDownListFor(m => m.Percentage,
                Model.GetSelectList(item.Key, ViewData["selectedPercentages"]),
                new {@class = "form-control", id = item.Key})
            </td>
        </tr>
    }
    </tbody>
</table>


回答4:

 @* @Html.DropDownListFor(x => x.GetAttribute_ID, new SelectList(Model.GetAttributes, "ID", "AttributeName", Model.GetAttribute_ID), "Select Attribute", new Dictionary<string, object>() { }) new { @id = "SelectAttribute", @name = "SelectAttribute[]", @class = "form-control dd" })*@
                        @Html.DropDownListFor(x => x.GetAttribute_ID, new SelectList(Model.GetAttributes, "ID", "AttributeName", Model.GetAttribute_ID), "Select Attribute", new Dictionary<string, object>() { { "class", "skill-level" }, { "data-val", "true" }, { "data-val-required", "Select skill level!"}})