Reputation: 37
I have some MVC3 Razor code. I am not so familiar with Razor but I can understand what the code is doing. I would like to clean this code up. Is there anything that could be done or is what I have the best possible?
@{ var i=1; foreach (var topic in @Model.Topic)
{
<option value="@topic.RowKey">@(i++). @topic.Description</option>
}
}
Upvotes: 1
Views: 95
Reputation: 15673
Looks like options for a select list, in which case you might want to be using the built-in @Html.SelectList
bits rather than looping through things and writing a string.
Upvotes: 0
Reputation: 74530
Personally, I'd merge the selection of the index of the item with the item in the sequence while iterating, like so:
@{ foreach (var topic in @Model.Topic.
Select((t, i) => new { Topic = t, Index = i + 1}))
{
<option value="@topic.RowKey">@(topic.Index).
@topic.Topic.Description</option>
}
}
This way, you don't have separation the indexing logic from the topic, it's all contained neatly within the anonymous type.
Upvotes: 1