Reputation: 3970
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.
Upvotes: 2
Views: 11856
Reputation: 1039598
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>
Upvotes: 4
Reputation: 15876
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 ;)
Upvotes: 4