Nested Query MVC LINQ

后端 未结 2 1516
抹茶落季
抹茶落季 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: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 Offers { get; set; }
    }
    

    Then in the controller

    IEnumerable 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
    @foreach (var service in Model)
    {
        

    @service.Name

    foreach (var item in service.Offers) { @item.ID @Html.DisplayFor(m => item.Offer) } }

提交回复
热议问题