1

I have a DB with a table with multiple rows. The first column of the table is the ID, the second is name and the third is surname. In every tutorial that I have watched they use a foreach and by using that they show all the information in their table. I want to know how can I show only the cells that I want. So for example I have 3 names and I want to show all the names I use:

@foreach (var item in Model)
{
<div>
    <div>@item.name</div>
    <h4>@item.surname</h4>
    <hr />
</div>
}

But how can I do to show only the second name and surname?

Thanks in advance!

1 Answer 1

1

Strictly using your sample code above, to get to the second element in Model, use an index. The second element is available as [1] (index is 0-based).

<div>
    <div>@Model[1].name</div>
    <h4>@Model[1].surname</h4>
    <hr />
</div>

To display the same information for a particular name value, such as John, you could use a foreach, testing each element, like this:

@foreach(var item in Model)
{
    @if(name == "John")
    {
        <div>
            <div>@item.name</div>
            <h4>@item.surname</h4>
            <hr />
        </div>
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Simple as that! Thank you very much! Can I do that but tell the code to search for the name? So for example I want to say: "Show me the name and surname of the row that has "John" on the 'name' field" ?
This will do the trick. Thank you very much one more time. Sorry I can't upvote your answer but I still have some reputation to obtain :-)
IMHO the filtering belongs to the Controller.
@CarlesCompany, I agree. However, I when I answered this I didn't have the time I felt I needed to write a tutorial on MVC and Razor, nor, given the question, did I feel it was needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.