好吧,我的下坠过去是这样做的:
<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循环来完成它。
发布于 2014-06-06 00:28:31
如何在您的模型中创建一个对象,该对象将包含您想要的所有项,然后将其传递给您的视图?示例:
在你的模型里。
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则是级别的集合。我希望这有助于解决你的问题。
https://stackoverflow.com/questions/24071618
复制相似问题