我有一个ASP.NET MVC视图,其中包含许多类似的代码,我试图弄清楚是否有办法合并它。以下是Question1的示例,我希望在18个问题中生成相同的内容。
<div class="editor-label">
@Html.LabelFor(model => model.Question1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Question1)
@Html.ValidationMessageFor(model => model.Question1)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Question1Type)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Question1Type)
@Html.ValidationMessageFor(model => model.Question1Type)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Question1Required)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Question1Required)
@Html.ValidationMessageFor(model => model.Question1Required)
</div>
有没有办法循环遍历所有问题的循环或MVC中的其他一些机制来整合18个问题的代码?
答案 0 :(得分:3)
看看这篇文章。它解释了如何从列表中绑定视图。 通过对ViewModel进行一些调整,我相信它对您也很有用。
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
答案 1 :(得分:1)
我觉得这样的事情会奏效:
@{
var properties = new List<Func<Model, object>>
{
model => model.Question1,
model => model.Question1Type,
model => model.Question1Required
};
}
@foreach( property in properties ) {
<div class="editor-label">
@Html.LabelFor(property )
</div>
<div class="editor-field">
@Html.EditorFor(property )
@Html.ValidationMessageFor(property )
</div>
}