0

进入页面时找不到任何解决方案以将另一个值作为默认值。这始终是我的第一价值。

创建“选择列表”

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

2 回答 2

6

您可以将 DropDownList 的重载用于扩展方法。

会是这样的

@Html.DropDownListFor(x=>x.LanguageId, new SelectList(Model.Language,"Value","Text"),"--Choose A Language --")
于 2013-05-13T14:30:24.153 回答
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)
于 2013-05-13T14:44:16.597 回答