2

I'm just starting out with mvc and have the following code:

@model AzureDemo.Models.User

@{
    ViewBag.Title = "Interests";
}

<h2>Interests</h2>

<p>
    @Html.ActionLink("Logout", "Logout")
</p>
<table>
    <tr>
        <th>
            Interests
        </th>
    </tr>

@foreach (var interest in Model.Interests) {
     <tr>
         <td>
            @Html.Display(interest)
        </td>
        //Tried like this
        <td>
            @Html.Display("id", interest.ToString())
        </td>
    </tr>
}

</table>

The Interests property in User is simply a list of strings. I'm trying to display each interest in a table for a user. I also tried putting a string like "test" in Html.Display, or tried using ToString() but still nothing.

2
  • why dont you direct use? like this : <td>@interest</td> Commented Feb 26, 2013 at 12:10
  • that worked! If you put it as an answer I will accept :) Commented Feb 26, 2013 at 13:33

2 Answers 2

4

You can use directly model item like this

@foreach (var interest in Model.Interests) {
 <tr>
     <td>
        @interest
    </td>
    // or this 
    <td>
        @interest.ToString()
    </td>
</tr>
}

or if you show html codes in your view then this is more safety

@foreach (var interest in Model.Interests) {
 <tr>
     <td>
        @Html.Raw(interest)
    </td>
</tr>
}

Also thanks for this chance ;)

Sign up to request clarification or add additional context in comments.

Comments

4

I'd recommend you using a display template and get rid of all foreach loops in your view:

@model AzureDemo.Models.User

@{
    ViewBag.Title = "Interests";
}

<h2>Interests</h2>

<p>
    @Html.ActionLink("Logout", "Logout")
</p>
<table>
    <thead>
        <tr>
            <th>
                Interests
            </th>
        </tr>
    </thead>
    <tbody>
        @Html.DisplayFor(x => x.Interests)
    </tbody>
</table>

and then define the corresponding display template which will automatically be rendered for each element of the Interests collection (~/Views/Shared/DisplayTemplates/Interest.cshtml):

@model AzureDemo.Models.Interest
<tr>
    <td>
        @Html.DisplayFor(x => x.Text)
    </td>
</tr>

1 Comment

Thanks I will try this out, however I already told AliRiza I would accept his answer :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.