0

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> } 
1
  • 1
    If your data is a single row, then you shouldn't pass in an IEnumerable into the view. Commented Mar 8, 2019 at 16:25

2 Answers 2

1

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) 
Sign up to request clarification or add additional context in comments.

Comments

0

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> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.