好的,我的下拉过去是这样的:
<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()
这个我无法解决的问题。
我需要两种解决方案中的一种。
Html.ValidationMessageFor()
使用此select
代码吗?如果没有,
2.我可以使用Html.DropDownListFor()
但是使用类似的for循环填充它吗?
例如,
@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)
上面的代码可以正常工作,但是我在编写所有SelectList值时,我希望有一个for循环为我做。
答案 0 :(得分:0)
如何在模型中创建一个对象,该对象将包含您想要的所有项目,然后将其传递给您的视图?例如:
在你的模特中。
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是级别的集合。 我希望这有助于解决您的问题。