Reputation: 782
I have an ASP.NET MVC view that contains a lot of similar code and I am trying to figure out if there is a way to consolidate it. Here is a sample for Question1, and I want to produce the same for 18 questions.
<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>
Is there a way to iterate through a loop for all the questions or some other mechanism in MVC to consolidate this code for 18 questions?
Upvotes: 0
Views: 154
Reputation: 8362
I think something like this will work:
@{
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>
}
Upvotes: 1
Reputation: 1128
Take a look at this article. It explain how to bind a view from a list. With just some adjustment on your ViewModel it can be useful also for you, I believe.
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Upvotes: 3