Reputation: 85
I am new to asp .net and MVC. I have a service method called Jumbo(). This method returns a list containing first name, last name and contact number. And I call this method from my main project as below. Also I return it to the view page.
var info = add.jumbo();
ViewData["sample"] = info;
return View("FormResults");
When I debugged the code the variable 'info' contains all the data I needed. The problem is how do I iterate the variable in html table using razor. I searched a lot to find a solution but I failed. Please help me with a solution. Thanks in advance.
Upvotes: 2
Views: 16621
Reputation: 31
@model Models.Nodes
@foreach (var item in Model)
{
<li>
<span> item.name </span>
</li>
}
Upvotes: 3
Reputation: 15545
Case 1: Basically you can observe this within your application itself. MVC itself provide you your answer. When ? When you creating View against the action which returning list. Say your action returning list of customer then you can observe following code.
@model IEnumerable<Customer>
<h2>Customers</h2>
<p>
@Html.ActionLink("Create New", "CreateCustomer", "ControllerName")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.ActionLink("Edit |", "UpdateCustomer", new { id = item.Id})
@Html.ActionLink("Details", "Details", new { id = item.Id})
@Html.ActionLink("Delete", "Delete", new { id = item.Id})
</td>
</tr>
}
</table>
Case 2: your scenario is when you sending the list within ViewData. Then you have to cast ViewData into respective model list and then you can perform same foreach loop. Action: var info = add.jumbo(); ViewData["sample"] = info;
return View("FormResults");
View:
@if (ViewData["sample"] != null)
{
List<Info> infoList = (List<Info>)ViewData["sample"];
foreach (var i in infoList)
{
//Perform your html here enclosed with html tags.
}
}
Upvotes: 4
Reputation: 384
In your view write a foreach loop as below
@model List<Object>
@foreach(var item in Model)
{
item.YourProperty;//without html
<label>@item.YourProperty</label> //in html
}
Upvotes: 2
Reputation: 3256
First you need to pass the model to the view:
return View("FormResults", info);
And in the view, you'll need to state the Type of model, and use @ to indicate code rather than html:
@model List<Foo> // Whatever your list is
@foreach (var item in Model)
{
<span>@item.Text</span>
}
Here's a blog about it in detail: http://weblogs.asp.net/scottgu/asp-net-mvc-3-new-model-directive-support-in-razor
Upvotes: 5