I\'m new to MVC and LINQ. Currently I faced difficulty on the project and decide to posted up.
My MVC-View that I
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
}
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>
}
}