MVC - Set selected value of SelectList

后端 未结 14 1194
后悔当初
后悔当初 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: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

提交回复
热议问题