Reputation: 49
I am learning MVC and for do this I am developing a "smart forum". How can I get value from Model directly , without foreach iteration when data is "a single row"?
@model IEnumerable<WebApplication28.ModelsFromDb.ArgomentiViewModel>
@foreach (var item in Model)
{
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.NomeArea)
</dt>
<dd>
@Html.DisplayFor(modelItem => item.NomeArea)
</dd>
}
Upvotes: 0
Views: 1797
Reputation: 2840
Your ActionMethod is going to have to only return a single row, not an IEnumerable. Use the SingleOrDefault() method on your entity. Return that in your view to ensure that you're only going to at most, return one row.
@model WebApplication28.ModelsFromDb.ArgomentiViewModel
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.NomeArea)
</dt>
<dd>
@Html.DisplayFor(modelItem => item.NomeArea)
</dd>
</dl>
Upvotes: 0
Reputation: 56688
That would be messy code if you keep your model type as IEnumerable<>
. So I suggest you change that, in one of two ways.
If you know there will always be a single item, why do you need to have a enumerable at all? Just remove it and make sure to return the underlying object from the controller:
@model WebApplication28.ModelsFromDb.ArgomentiViewModel
If you have to deal with collections, I bet it is a more specific type you are returning from the controller. If it is a list, you could use IList<>
, which has many more operations, and which you could index:
@model IList<WebApplication28.ModelsFromDb.ArgomentiViewModel>
...
@Html.DisplayNameFor(model => model[0].NomeArea)
Upvotes: 1