Nested Query MVC LINQ

后端 未结 2 1413
抹茶落季
抹茶落季 2021-01-13 15:44

I\'m new to MVC and LINQ. Currently I faced difficulty on the project and decide to posted up.

My MVC-View that I

相关标签:
2条回答
  • 2021-01-13 15:55

    ViewBag is a dynamic property you can insert ViewBag anything but when you retrieve data from ViewBag, first need to convert it.

    @foreach (var item in (List<PS>)ViewBag.services){
        <h3 class="page-header">
            @item
        </h3>
    
        //Table TAG INSERT Here: ID, Offer, Service
    }
    
    0 讨论(0)
  • 2021-01-13 15:58

    You can use a .GroupBy() clause to group your data by Service. Start by creating view models to represent what you want to display in the view

    public class OfferVM
    {
        public int ID { get; set; }
        [DisplayFormat(DataFormatString = "{0:P0}")]
        public float Offer { get; set; } // assumes you store this as float in the db
    }
    public class ServiceVM
    {
        public string Name { get; set; }
        public IEnumerable<OfferVM> Offers { get; set; }
    }
    

    Then in the controller

    IEnumerable<ServiceVM> model = db.PS.GroupBy(x => x.Service).Select(x => new ServiceVM()
    {
        Name = x.Key,
        Offers = x.Select(y => new OfferVM()
        {
            ID = y.ID,
            Offer = y.Offer
        })
    });
    return View(model);
    

    And in the view

    @model IEnumerable<ServiceVM>
    @foreach (var service in Model)
    {
        <h2>@service.Name</h2>
        foreach (var item in service.Offers)
        {
            <span>@item.ID</span>
            <span>@Html.DisplayFor(m => item.Offer)</span>
        }
    }
    
    0 讨论(0)
提交回复
热议问题