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

时间:2013-05-13 14:28:00

标签: c# asp.net-mvc html-helper

无法找到任何解决方案,以便在进入页面时将其他值作为默认值。这始终是我的第一个价值。

创建“选择列表”

            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() });
        }

视图模型:

    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"))

2 个答案:

答案 0 :(得分:6)

您可以使用DropDownList的this重载作为扩展方法。

会是这样的

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

答案 1 :(得分:3)

为什么不提供默认语言作为参数?另一件事,将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)