常用函数生成多个视图页面
问题描述:
我有一个包含有选择多个下拉菜单像常用函数生成多个视图页面
<option>1<option>
<option>2<option>
<option>3<option>
和
<option>-5<option>
<option>-6<option>
<option>-7<option>
所以我有一个函数创建生成页面上下拉剃刀视图中的下拉选项。
@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;
}
}
现在在剃刀你只需要使用类为:
GeneratorHelper.GenerateDropDown(1,5);
@Achillius感谢我装箱助手类,而不是对类的静态,改成了现在的作品精细 –