默认值/ Html.DropDownListFor中的加载值

本文关键字:加载 DropDownListFor Html 默认值 | 更新日期: 2023-09-27 18:13:22

无法找到在进入页面时将另一个值作为默认值的解决方案。它总是我的第一个值

创建"selectlist"

            List<SelectListItem> list = new List<SelectListItem>();
        var x = 0;
        foreach (var lang in Enum.GetValues(typeof(ResourceHandler.Languages)))
        {
            list.Add(new SelectListItem { Selected = x == langInt, Value = x++.ToString(), Text = lang.ToString() });
        }

viewmodel:

    public class SettingsViewModel
{
    public int LanguageId { get; set; }
    public List<SelectListItem> Language { get; set; }
}

视图:

@Html.DropDownListFor(x=>x.LanguageId, new SelectList(Model.Language,"Value","Text"))

默认值/ Html.DropDownListFor中的加载值

你可以使用这个重载的DropDownList for扩展方法。

就像这样

@Html.DropDownListFor(x=>x.LanguageId, new SelectList(Model.Language,"Value","Text"),"--Choose A Language --")

为什么不提供默认语言作为参数呢?另外,将List更改为SelectList会使事情变得更容易。

public class SettingsViewModel
{
    public int LanguageId { get; set; }
    public SelectList Language { get; set; }
    public int? DefaultLanguageId {get; set;}
    public SettingsViewModel()
    {
       CreateSelectList();
    }     
    public SettingsViewModel(int? defaultLanguageId)
    {
        DefaultLanguageId = defaultLanguageId;
        CreateSelectList();
    }
    private void CreateSelectList()
    {
        List<SelectListItem> list = new List<SelectListItem>();
        var x = 0;
        foreach (var lang in Enum.GetValues(typeof(ResourceHandler.Languages)))
        {
            list.Add(new SelectListItem { Selected = x == langInt, Value = x++.ToString(), Text = lang.ToString() });
            if(DefaultLanguageId != null)
               SelectList = new SelectList(list, "Value", "Text", DefaultLanguageId)
            else
               SelectList = new SelectList(list, "Value", "Text") 
        }
    }    

然后视图:

@Html.DropDownListFor(x => x.LanguageId, Model.Language)