Med Elgarnaoui
Med Elgarnaoui

Reputation: 1667

How to show data from query in table on asp.net

   var query =  (from p in db.Produits
                     join v in db.Vondus on p.ProduitId equals v.ProduitId
                     where p.CentreId == centre.CentreId
                     select new
                     {
                         nom = p.ProduitNom,
                         date = v.VonduDate,
                         prix = p.ProduitPrix
                     }).ToList();

I want to show this query in html table. can you help me please

Upvotes: 0

Views: 406

Answers (1)

Win
Win

Reputation: 62290

Easiest way is to assign the result into a Model, and send it to View.

Model

namespace DemoMvc.Models
{
    public class ProduitModel
    {
        public string ProduitNom { get; set; }
        public DateTime VonduDate { get; set; }
        public string ProduitPrix { get; set; }
    }
}

Action Method

public ActionResult Index()
{
    var result = (from p in db.Produits
                    join v in db.Vondus on p.ProduitId equals v.ProduitId
                    where p.CentreId == centre.CentreId
                    select new ProduitModel
                    {
                        nom = p.ProduitNom,
                        date = v.VonduDate,
                        prix = p.ProduitPrix
                    }).ToList();
    return View(result);
}

View

Make sure model's namespace match the actual namespace.

@model IEnumerable<DemoMvc.Models.ProduitModel>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <table class="table table-bordered">
        <tr>
            <th>ProduitNom</th>
            <th>VonduDate</th>
            <th>ProduitPrix</th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.ProduitNom</td>
                <td>@item.VonduDate.ToShortDateString()</td>
                <td>@item.ProduitPrix</td>
            </tr>
        }
    </table>
</body>
</html>

Result

enter image description here

Upvotes: 1

Related Questions