Neo
Neo

Reputation: 16239

How do I bind my List model to View?

I'm using mvc4 having following code with controller.cs

public class GroupsController : Controller
{
    //
    // GET: /Groups/


    public ActionResult Index()
    {
        IGroupRepository groupRepo = new GroupRepository();

        var mygrouplist = groupRepo.GetAll().ToList();

        return View("Groups",mygrouplist);
    }

Now on Groups.cshtml

how can i bind mygrouplist values to

<h4 class="profile-namegrp"><a href="#">GroupName</a> </h4>

Upvotes: 0

Views: 51

Answers (3)

MichaC
MichaC

Reputation: 13410

Did you read any tutorial so far? If not, consider reading this one

It is pretty easy to data bind stuff with razor

example

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Title)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.ReleaseDate)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Genre)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Price)
    </td>
     <th>
        @Html.DisplayFor(modelItem => item.Rating)
    </th>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
        @Html.ActionLink("Details", "Details", { id=item.ID })  |
        @Html.ActionLink("Delete", "Delete", { id=item.ID }) 
    </td>
</tr>
}

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039488

You could use a foreach loop to go through the values of the model. First you should make your view strongly typed to a List<T> using the @model directive where T is the type of the collection you are passing:

@model List<YourListType>

<h4 class="profile-namegrp">
    <a href="#">GroupName</a>
</h4>

@foreach (var item in Model)
{
    <div>@item.SomeProperty</div>
}

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101731

Simply you can use a foreach loop:

foreach(var item in Model)
{
  <h4 class="profile-namegrp"><a href="#">@item.Property</a> </h4>  
}

Model represents your View model, as i see you already pass your model so this should work.

PS: Don't forget to set your View model like:

@model IEnumerable<MyGroup>

Upvotes: 0

Related Questions