Qiang Qiang - 9 months ago 22
C# Question

ASP.NET : Unable to present data from view model in view

I'd just started using ASP.NET and are training through a lot of tutorials from youtube and googles that I can find.

But I can't seem to find a solutions to this.

My purpose is to generate a table view of Customers into the table to list as c1 and c2 using viewmodel.

My viewmodel code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Alpha.Models;

namespace Alpha.ViewModels
{
public class ListCustomersViewModel
{
public List<Customer> Customers { get; set; }
}
}


My Controller code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Alpha.Models;
using Alpha.ViewModels;


namespace Alpha.Controllers
{
public class CustomersController : Controller
{
// GET: Customers/ListCustomer
public ActionResult ListCustomers()
{
var customers = new List<Customer>
{
new Customer { Name = "C1" , Id = 1},
new Customer { Name = "C2" , Id = 2}
};
var viewModel = new ListCustomersViewModel
{
Customers = customers
};
return View(viewModel);
}
}
}


My View code:

@model Alpha.ViewModels.ListCustomersViewModel
@{
ViewBag.Title = "ListCustomers";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Customers</h1>

<div class="container">
<table class="table">
<thread>
<tr>
<th>Customer</th>
</tr>
</thread>
<tbody>
<tr>
<td>*I DONT KNOW WHAT I SHOULD TYPE HERE TO PASS THE INFORMATION IN (C1)</td>
<td>*I DONT KNOW WHAT I SHOULD TYPE HERE TO PASS THE INFORMATION IN (C2)</td>
</tr>
</tbody>
</table>
</div>


I really hope some one can give me a guide on this thing. Thank you.

Answer Source

You need to loop over your model and extract the info to build the table

<tbody>
@foreach (var item in Model.Customers)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Id)
        </td>
    </tr>
}
</tbody>