填补选择列表与一个for循环 [英] Filling in the SelectList with a for loop
问题描述
好吧,我的下拉用来进行像这样:
Ok, my drop down used to be made like so:
<select id="Level" onchange="showChoice(this.value);">
<option id="0" value="0">Pick a Level</option>
@for (int i =1; i <= Model.ExamplesCount; i++ )
{
<option id="@i" value="@i">Level @i</option>
}
</select>
由于ExamplesCount数每用户改变。但我需要使用 Html.ValidationMessageFor()
的事情,我不能得到这个工作。
because the ExamplesCount number changes per user. But I need to use the Html.ValidationMessageFor()
thing, which I can't get to work with this.
我需要两个解决方案之一。
I need one of two solutions.
- 我可以
Html.ValidationMessageFor()
此工作选择
标记?
- Can I make
Html.ValidationMessageFor()
work with thisselect
tag?
,或者如果没有,
2,可我用 Html.DropDownListFor()
但有类似的for循环填充它吗?
2.Can I use Html.DropDownListFor()
but fill it in with a similar for loop?
例如,
@Html.DropDownListFor(
m => m.Level,
new SelectList(
new List<Object> {
new {value = 0, text ="Pick a Level"},
new { value = 1, text = "Level 1"},
new { value = 2, text = "Level 2" },
new { value = 3, text = "Level 3" },
new { value = 4, text = "Level 4" },
new { value = 5, text = "Level 5" }
},
"value", "text", null))
@Html.ValidationMessageFor(model => model.Level)
以上code ++工程,但如果我硬编码的所有选择列表的价值观,我想有一个for循环,做对我来说。
The above code works, but where I am hard coding all the SelectList values, I'd like to have an for loop that does it for me.
推荐答案
有关创建模型中的对象,将内容的所有你想要的,然后传递到您的视图中的项目是什么?例如:
What about creating a object in your model that will content all the items you want an then pass that to your view? Example:
在你的模型。
public class Model{
...other properties
public List<ListItemSource> myLevels { get; set; }
[Required(ErrorMessage = @"*Required")]
public string Level { get; set; }
}
在你的控制器:
public ActionResult YourAction(Model myModel)
{
var myModel = new Model
{
myLevels =methodToGetLevels()
};
return view(myModel);
}
在您查看:
@Html.DropDownListFor(x => x.Level,
new SelectList(Model.myLevels, "Value", "Text"))
@Html.ValidationMessageFor(model => model.Level)
在哪里x.Level将举行选定值和Model.myLevels是水平的集合。
我希望这有助于解决您的问题。
Where x.Level will hold the selected value and Model.myLevels is the collection of levels. I hope this help to solve your problem.
这篇关于填补选择列表与一个for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!