剃须刀视图中的常用功能,用于在多个视图页面中生成下拉列表



我有一个页面,其中包含多个下拉列表,选项如下

<option>1<option>
<option>2<option>
<option>3<option>

<option>-5<option>
<option>-6<option>
<option>-7<option>

所以我创建了一个函数来在 Razor 视图中生成下拉选项。

 @functions {
        public List<SelectListItem> GenerateDropDown(int startvalue, int endValue)
        {
            var dropDownList = new List<SelectListItem>();
            for (int i = startvalue; i <= endValue; i++)
            {
                string val = i.ToString();
                dropDownList.Add(new SelectListItem { Text = val, Value = val });
            }
            return dropDownList;
        }
}

并像这样使用

 @Html.DropDownListFor(m => m.xyz, GenerateDropDown(1, 10))
 @Html.DropDownListFor(m => m.Abc, GenerateDropDown(2, 20))

这工作正常,但我想在多个页面中使用相同的函数,而没有代码重复,我尝试使用帮助程序方法,但没有用任何人可以建议我如何集中 GenerateDropDown 函数。

创建静态类,其中包含静态方法 GenerateDropDown。

比方说

       public static class GeneratorHelper{
         public static List<SelectListItem> GenerateDropDown(int startvalue, int endValue)
            {
                var dropDownList = new List<SelectListItem>();
                for (int i = startvalue; i <= endValue; i++)
                {
                    string val = i.ToString();
                    dropDownList.Add(new SelectListItem { Text = val, Value = val });
                }
                return dropDownList;
            }
       }

现在在 Razor 中,您只需将类用作:

GeneratorHelper.GenerateDropDown(1,5);

最新更新