MVC - Set selected value of SelectList

后端 未结 14 1137
后悔当初
后悔当初 2020-12-13 08:03

How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;

SelectList selectList = new SelectList(items, \"I         


        
相关标签:
14条回答
  • 2020-12-13 08:40

    If you have your SelectList object, just iterate through the items in it and set the "Selected" property of the item you wish.

    foreach (var item in selectList.Items)
    {
      if (item.Value == selectedValue)
      {
        item.Selected = true;
        break;
      }
    }
    

    Or with Linq:

    var selected = list.Where(x => x.Value == "selectedValue").First();
    selected.Selected = true;
    
    0 讨论(0)
  • 2020-12-13 08:42

    I usually use this method

            public static SelectList SetSelectedValue(SelectList list, string value)
        {
            if (value != null)
            {
                var selected = list.Where(x => x.Value == value).First();
                selected.Selected = true;
                return list;
            }
            return list;
        }
    
    0 讨论(0)
  • 2020-12-13 08:43

    You can use below method, which is quite simple.

    new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault());
    

    This will auto-select the first item in your list. You can modify the above query by adding a where clause.

    0 讨论(0)
  • 2020-12-13 08:44

    Further to @Womp answer, it's worth noting that the "Where" Can be dropped, and the predicate can be put into the "First" call directly, like this:

    list.First(x => x.Value == "selectedValue").Selected = true;

    0 讨论(0)
  • 2020-12-13 08:46

    In case someone is looking I reposted my answer from: SelectListItem selected = true not working in view

    After searching myself for answer to this problem - I had some hints along the way but this is the resulting solution for me. It is an extension Method. I am using MVC 5 C# 4.52 is the target. The code below sets the Selection to the First Item in the List because that is what I needed, you might desire simply to pass a string and skip enumerating - but I also wanted to make sure I had something returned to my SelectList from the DB)

    Extension Method:
    

    public static class SelectListextensions {

    public static System.Web.Mvc.SelectList SetSelectedValue
    

    (this System.Web.Mvc.SelectList list, string value) { if (value != null) { var selected = list.Where(x => x.Text == value).FirstOrDefault(); selected.Selected = true;
    } return list; }
    }

    And for those who like the complete low down (like me) here is the usage. The object Category has a field defined as Name - this is the field that will show up as Text in the drop down. You can see that test for the Text property in the code above.

    Example Code:
    

    SelectList categorylist = new SelectList(dbContext.Categories, "Id", "Name");

    SetSelectedItemValue(categorylist);

    select list function:
    

    private SelectList SetSelectedItemValue(SelectList source) { Category category = new Category();

    SelectListItem firstItem = new SelectListItem();
    
    int selectListCount = -1;
    
    if (source != null && source.Items != null)
    {
        System.Collections.IEnumerator cenum = source.Items.GetEnumerator();
    
        while (cenum.MoveNext())
        {
            if (selectListCount == -1)
            {
                selectListCount = 0;
            }
    
            selectListCount += 1;
    
            category = (Category)cenum.Current;
    
            source.SetSelectedValue(category.Name);
    
            break;
        }
        if (selectListCount > 0)
        {
            foreach (SelectListItem item in source.Items)
            {
                if (item.Value == cenum.Current.ToString())
                {
                    item.Selected = true;
    
                    break;
                }
            }
        }
    }
    return source;
    

    }

    You can make this a Generic All Inclusive function / Extension - but it is working as is for me

    0 讨论(0)
  • 2020-12-13 08:48

    A bit late to the party here but here's how simple this is:

    ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82");
    

    this uses my method getcountries to populate a model called countries, obviousley you would replace this with whatever your datasource is, a model etc, then sets the id as the value in the selectlist. then just add the last param, in this case "82" to select the default selected item.

    [edit] Here's how to use this in Razor:

    @Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" })
    

    Important: Also, 1 other thing to watch out for, Make sure the model field that you use to store the selected Id (in this case model.CountryId) from the dropdown list is nullable and is set to null on the first page load. This one gets me every time.

    Hope this saves someone some time.

    0 讨论(0)
提交回复
热议问题