asp.net,mvc:如何在多个html文件中共享相同的下拉列表?

时间:2015-04-11 21:34:33

标签: asp.net-mvc razor

我在多个cshtml文件中使用了以下内容:

@{
    var grades = new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = "--- Select your grade level ---", Value = "", Disabled= true},

        new SelectListItem { Selected = false, Text = "K", Value = "K"},
        new SelectListItem { Selected = false, Text = "1", Value = "1st"},
        new SelectListItem { Selected = false, Text = "2", Value = "2nd"},
        new SelectListItem { Selected = false, Text = "3", Value = "3rd"},
        new SelectListItem { Selected = false, Text = "4", Value = "4th"},
        new SelectListItem { Selected = false, Text = "5", Value = "5th"},
        new SelectListItem { Selected = false, Text = "6", Value = "6th"},
        new SelectListItem { Selected = false, Text = "7", Value = "7th"},
        new SelectListItem { Selected = false, Text = "8", Value = "8th"},
        new SelectListItem { Selected = false, Text = "9", Value = "9th"},
        new SelectListItem { Selected = false, Text = "10", Value = "10th"},
        new SelectListItem { Selected = false, Text = "11", Value = "11th"},
        new SelectListItem { Selected = false, Text = "12", Value = "12th"},
    };
}

重用这些数据而不是在多个文件中复制/粘贴的更好方法是什么?

非常感谢!

1 个答案:

答案 0 :(得分:2)

如果这是静态数据,那么只需创建一个静态助手类。

public static class Helper
{
    public static List<SelectListItem> GetGradeLevels()
    {
        return new List<SelectListItem>
        {
            new SelectListItem { Selected = true, 
                Text = "--- Select your grade level ---", 
                Value = "", Disabled= true},

            new SelectListItem { Selected = false, Text = "K", Value = "K"},
            new SelectListItem { Selected = false, Text = "1", Value = "1st"},
            new SelectListItem { Selected = false, Text = "2", Value = "2nd"},
            new SelectListItem { Selected = false, Text = "3", Value = "3rd"},
            new SelectListItem { Selected = false, Text = "4", Value = "4th"},
            new SelectListItem { Selected = false, Text = "5", Value = "5th"},
            new SelectListItem { Selected = false, Text = "6", Value = "6th"},
            new SelectListItem { Selected = false, Text = "7", Value = "7th"},
            new SelectListItem { Selected = false, Text = "8", Value = "8th"},
            new SelectListItem { Selected = false, Text = "9", Value = "9th"},
            new SelectListItem { Selected = false, Text = "10", Value = "10th"},
            new SelectListItem { Selected = false, Text = "11", Value = "11th"},
            new SelectListItem { Selected = false, Text = "12", Value = "12th"}};
    }
}

然后在你的cshtml中,只需:

@Html.DropDownListFor(x => x.Whatever, Helper.GetGradeLevels())