I have a list of data. I need to convert the list rows into columns. I searched a lot for this but couldn't find a solution for this.
My Action Method:
public ActionResult Index()
{
var obj = JsonConvert.DeserializeObject<XLDataManager>(new DataUploadService().GetDataUpload(1, 1));
XLDataManager excelData = (XLDataManager)obj;
List<Design> listData = new List<Design>()
{
excelData.CurrentPlan,
excelData.Design1,
excelData.Design2,
excelData.Design3,
excelData.Design4
};
foreach (var items in ListDesign)
{
DesignViewModel objDesignViewModel = new DesignViewModel()
{
TotalPMPMCost_29 = items.TotalPMPMCost_29,
PlanType_30 = items.PlanType_30,
ServicesCoveredDeductible_31 = items.ServicesCoveredDeductible_31,
ContributionType_32 = items.ContributionType_32,
ContributionAmount_33 = items.ContributionAmount_33,
MedicalDeductible_36 = items.MedicalDeductible_36,
MedicalCoinsurance_37 = items.MedicalCoinsurance_37,
MedicalOutofPocketMax_38 = items.MedicalOutofPocketMax_38
};
DesignViewModelList.Add(objDesignViewModel);
}
return View(DesignViewModelList);
}
Model Class:
public class DesignViewModel
{
public float TotalPMPMCost_29 { get; set; }
public string PlanType_30 { get; set; }
public string ServicesCoveredDeductible_31 { get; set; }
public string ContributionType_32 { get; set; }
public float ContributionAmount_33 { get; set; }
public float MedicalDeductible_36 { get; set; }
public float MedicalCoinsurance_37 { get; set; }
public float MedicalOutofPocketMax_38 { get; set; }
}
View:
#model IEnumerable<HealthAppDesign.ViewModel.DesignViewModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.TotalPMPMCost_29)
</th>
<th>
#Html.DisplayNameFor(model => model.PlanType_30)
</th>
<th>
#Html.DisplayNameFor(model => model.ServicesCoveredDeductible_31)
</th>
<th>
#Html.DisplayNameFor(model => model.ContributionType_32)
</th>
<th>
#Html.DisplayNameFor(model => model.ContributionAmount_33)
</th>
<th>
#Html.DisplayNameFor(model => model.MedicalDeductible_36)
</th>
<th>
#Html.DisplayNameFor(model => model.MedicalCoinsurance_37)
</th>
<th>
#Html.DisplayNameFor(model => model.MedicalOutofPocketMax_38)
</th>
</tr>
#foreach
(var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.TotalPMPMCost_29)
</td>
<td>
#Html.DisplayFor(modelItem => item.PlanType_30)
</td>
<td>
#Html.DisplayFor(modelItem => item.ServicesCoveredDeductible_31)
</td>
<td>
#Html.DisplayFor(modelItem => item.ContributionType_32)
</td>
<td>
#Html.DisplayFor(modelItem => item.ContributionAmount_33)
</td>
<td>
#Html.DisplayFor(modelItem => item.MedicalDeductible_36)
</td>
<td>
#Html.DisplayFor(modelItem => item.MedicalCoinsurance_37)
</td>
<td>
#Html.DisplayFor(modelItem => item.MedicalOutofPocketMax_38)
</td>
</tr>
}
</table>
I just need to display the data like below:
Current Plan Design 1 Design 2 Design 3 Design 4
Total PMPM Cost $1,000.00 $988.87 $1,254.39 $1,155.83 $1,201.74
Plan Type HMO PPO PPO HMO HMO
Services Covered All Services All Services All Services All Services All Services
Contribution Type Dollar Percent Dollar Dollar Dollar
Contribution Amount 450 0.3 200 400 300
Deductible $1,500 $4,000 $2,000 $1,500 $1,500
Coinsurance 20% 20% 0% 0% 0%
Out of Pocket Maximum $3,000 $8,000 $4,000 $3,000 $3,000
Currently it is displaying rows as columns..
An immediate help will be appreciated. Kindly let me know if any more code is required.
Thanks
You will need to iterate through the list of view models for every row:
<table>
<thead>
<tr>
<th><!-- Empty column for labels --></th>
#foreach (var item in Model) {
<th>#Html.DisplayNameFor(model => model.Name)</th>
}
</tr>
</thead>
<tbody>
<tr>
<td>Total PMPM Cost</td>
#foreach (var item in Model) {
<td>#Html.DisplayFor(modelItem => item.TotalPMPMCost_29)</td>
}
</tr>
<tr>
<td>Plan Type</td>
#foreach (var item in Model) {
<td>#Html.DisplayFor(modelItem => item. PlanType_30)</td>
}
</tr>
<!-- Repeat for all model properties -->
</tbody>
</table>
Related
I have two tables. One is Booking and other is Course. Course can have many Bookings.
I want to count number of Bookings for each Course and pass that to ViewBag. So I want to count how many users applied for each Course.
This line counts total number o Bookings but I cant figure out how to do that for each Course.
ViewBag.Counter = db.Bookings.Count();
This line gets all the courses to my Index page.
IEnumerable<Course> courses = cr.GetCourses();
return View(courses.ToList());
And this is controller that is doing the work. I tried with 2 foreach loops but cant get it to work.
public ActionResult Index()
{
Booking booking = new Booking();
Course course = new Course();
List<Course> listCourses = new List<Course>();
List<Booking> bookings = new List<Booking>();
foreach (var item in listCourses)
{
int id = course.CourseId;
foreach (var item1 in bookings)
{
ViewBag.Counter = db.Bookings.Where(x => x.CourseId == id).Count();
}
}
IEnumerable<Course> courses = cr.GetCourses();
return View(courses.ToList());
}
I expect to get a number of users that applied for each course that is listed on my index page. I got no exceptions or errors and nothing shows up in my view. When I use ViewBag.Counter = db.Bookings.Count(); I get a total number of users that applied for all avaliable courses. Model on the view is Course model which is in relation with Booking with one to many relation.
This is the View for my ActionResult.
#model IEnumerable<Entities.Course>
#{
ViewBag.Title = "AlgebraSchoolApp";
}
<h2>Dobrodošli!</h2>
<p>
Da bi se prijavili na neki od naših tečajeva kliknite na link prijave:
<button>
#Html.ActionLink("Prijava","Create","Booking")
</button>
</p>
<h2> Svi tečajevi</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CourseName)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayName("Broj polaznika")
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CourseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#ViewBag.Counter
</td>
</tr>
}
</table>
<h2>Slobodni tečajevi</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CourseName)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
</tr>
#foreach (var item in Model.Where(x => x.Full == false))
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CourseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
</tr>
}
</table>
The reason that ViewBag.Counter is showing the same result for all courses is because it is being overwritten each time with ViewBag.Counter = db.Bookings.Where(x => x.CourseId == id).Count();.
If i have understood your issue this can be fixed by creating a new view model to store the required information for a course and return this to your view. EG:
public class CourseViewModel
{
public string CourseName { get; set; }
public string Description { get; set; }
//etc
public int BookingCount { get; set; }
}
Controller:
public ActionResult Index()
{
var courses = cr.GetCourses();
var courseViewModels= new List<CourseViewModel>();
foreach (var course in courses )
{
var bookingCount = db.Bookings.Where(x => x.CourseId == course.CourseId).Count();
courseViewModels.Add(new CourseViewModel{
CourseName = course.CourseName, //Add all the vm properties
BookingCount = bookingCount
});
}
return View(courseViewModels);
}
In the view:
#model IEnumerable<CourseViewModel>
#/*...*/
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CourseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.BookingCount )
</td>
</tr>
}
I have 2 filled ILists Suppliers and VwSrmAhmSuppliers with a common property Supplier.SupplierNo and VwSrmAhmSupplier.AhmSupplierNo. I'd like to combine them on that common property into one IList where the individual class properties are still accessible so I can efficiently access them in the View.
So if I pulled the first item in CommonList and then asked for CommonList(1).Supplier.SupplierNo and CommonList(1).VwAhmSrmSupplier.AhmSupplierNo - those 2 fields would be the same.
Maybe I have a class like this:
public class SupplierDetail
{
public Supplier Supplier { get; set; }
public Models.ExternalData.VwSrmAhmSupplier VwSrmAhmSupplier { get;set;}
}
public IList<Supplier> Suppliers { get;set; }
public IList<Models.ExternalData.VwSrmAhmSupplier> VwSrmAhmSuppliers { get; set; }
public IList<SupplierDetail> SupplierDetails;
public async Task OnGetAsync(Boolean? All)
{
//don't show all records unless explicity asked to!
if (All == true)
{
Suppliers = await _context.Supplier
.Include(s => s.Status)
.Include(c => c.Category)
.Include(c => c.Comments)
.OrderByDescending(c => c.CreateDate)
.ToListAsync();
var supplierNos = Suppliers.Select(s => s.SupplierNo).ToList();
VwSrmAhmSuppliers = await _externalcontext.VwSrmAhmSuppliers
.Where(v => supplierNos
.Any(s => s == v.AhmSupplierNo))
.ToListAsync();
SupplierDetails = ??
}
The HTML table I'm trying to generate would be something like this:
<tbody>
#foreach (var item in Model.CommonList)
{
<tr>
<td>
<a asp-page="./Details" asp-route-id="#item.Id">#Html.DisplayFor(modelItem => item.Supplier.SupplierNo)</a>
</td>
<td>
#Html.DisplayFor(modelItem => item.VwSrmAhmSupplier.AhmSupplierNm)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.CreateDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Creator)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Category.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Status.Description)
</td>
<td>
<a asp-page="./Delete" asp-route-id="#item.Id" class="btn btn-danger">Hide</a>
</td>
</tr>
}
</tbody>
Thanks #Selvin for the help in leading me down the right path.
Create a composite class of 2 classes
public class SupplierDetail
{
public Supplier Supplier { get; set; }
public VwSrmAhmSupplier VwSrmAhmSupplier { get;set;}
}
Then, fill the list by looping:
SupplierDetails = new List<SupplierDetail>();
foreach (Supplier supplier in Suppliers)
{
SupplierDetail supplierDetail = new SupplierDetail
{
Supplier = supplier,
VwSrmAhmSupplier = VwSrmAhmSuppliers.Where(s => s.AhmSupplierNo == supplier.SupplierNo).First()
};
SupplierDetails.Add(supplierDetail);
}
Finally, access your object properties in the view
<table id="table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].Supplier.SupplierNo)
</th>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].VwSrmAhmSupplier.AhmSupplierNm)
</th>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].Supplier.CreateDate)
</th>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].Supplier.Creator)
</th>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].Supplier.Category)
</th>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].Supplier.Status)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.SupplierDetails)
{
<tr>
<td>
<a asp-page="./Details" asp-route-id="#item.Supplier.Id">#Html.DisplayFor(modelItem => item.Supplier.SupplierNo)</a>
</td>
<td>
#Html.DisplayFor(modelItem => item.VwSrmAhmSupplier.AhmSupplierNm)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.CreateDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Creator)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Category.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Status.Description)
</td>
<td>
<a asp-page="./Delete" asp-route-id="#item.Supplier.Id" class="btn btn-danger">Hide</a>
</td>
</tr>
}
</tbody>
</table>
Trying to get this to work but keep getting null values from the Model.
Controller:
[HttpPost]
public ActionResult Index(OPISPriceReportOLY_Result model)
{
if (ModelState.IsValid)
{
int id = model.orpid;
using (var context = new IntranetCoreEntities())
{
var selected = context.OPISRetailPricings.Find(id);
selected.DMarkup = model.DMarkup;
selected.DSell = model.DSell;
selected.RMarkup = model.RMarkup;
selected.RSell = model.RSell;
context.SaveChanges();
}
}
return View("Index", model);
}
View:
#model IEnumerable<OPIS7.Models.OPISPriceReportOLY_Result>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("Index", "OPISPriceReportOLY_Result", FormMethod.Post))
{
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.cpid)
</th>
<th>
#Html.DisplayNameFor(model => model.Zone)
</th>
<th>
#Html.DisplayNameFor(model => model.ZoneDescription)
</th>
<th>
#Html.DisplayNameFor(model => model.Rack)
</th>
<th>
#Html.DisplayNameFor(model => model.ActualProduct)
</th>
<th>
#Html.DisplayNameFor(model => model.Cost)
</th>
<th>
#Html.DisplayNameFor(model => model.DMarkup)
</th>
<th>
#Html.DisplayNameFor(model => model.DSell)
</th>
<th>
#Html.DisplayNameFor(model => model.RMarkup)
</th>
<th>
#Html.DisplayNameFor(model => model.RSell)
</th>
<th>
#Html.DisplayNameFor(model => model.DateUpdated)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.cpid)
</td>
<td>
#Html.DisplayFor(modelItem => item.Zone)
</td>
<td>
#Html.DisplayFor(modelItem => item.ZoneDescription)
</td>
<td>
#Html.DisplayFor(modelItem => item.Rack)
</td>
<td>
#Html.DisplayFor(modelItem => item.ActualProduct)
</td>
<td>
#Html.DisplayFor(modelItem => item.Cost)
</td>
<td>
#Html.TextBoxFor(modelItem => item.DMarkup)
</td>
<td>
#Html.TextBoxFor(modelItem => item.DSell)
</td>
<td>
#Html.TextBoxFor(modelItem => item.RMarkup)
</td>
<td>
#Html.TextBoxFor(modelItem => item.RSell)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateUpdated)
</td>
<td>
<button type="submit">Update</button>
</td>
</tr>
}
</table>
}
Model:
namespace OPIS7.Models
{
using System;
using System.ComponentModel.DataAnnotations;
public partial class OPISPriceReportOLY_Result
{
[Key]
public int orpid { get; set; }
public int cpid { get; set; }
public string Zone { get; set; }
public string ZoneDescription { get; set; }
public string Rack { get; set; }
public string ActualProduct { get; set; }
public Nullable<double> Cost { get; set; }
public Nullable<double> DMarkup { get; set; }
public string DSell { get; set; }
public Nullable<double> RMarkup { get; set; }
public Nullable<double> RSell { get; set; }
public Nullable<System.DateTime> DateUpdated { get; set; }
}
}
According to documentation this is supposed to work without having to resort to AJAX or JS of any kind but I'm hitting a wall. Any ideas?
If you just want to take single OPISPriceReportOLY_Result in action method, you will need to move form tag inside for loop.
The clean approach is to create a Partial View. You can read more at Adam Freeman's book.
Index.cshtml
#model IEnumerable<OPISPriceReportOLY_Result>
<table class="table">
#foreach (var item in Model)
{
#Html.Partial("_Result", item)
}
</table>
_Result.cshtml
#model OPISPriceReportOLY_Result
#using (Html.BeginForm("Update", "Home", FormMethod.Post))
{
<tr>
<td>
#Html.DisplayFor(x => x.cpid)
#Html.HiddenFor(x => x.cpid)
</td>
<td>
#Html.DisplayFor(x => x.Zone)
#Html.HiddenFor(x => x.Zone)
</td>
<td>
#Html.DisplayFor(x => x.ZoneDescription)
#Html.HiddenFor(x => x.ZoneDescription)
</td>
<td>
#Html.DisplayFor(x => x.Rack)
#Html.HiddenFor(x => x.Rack)
</td>
<td>
#Html.DisplayFor(x => x.ActualProduct)
#Html.HiddenFor(x => x.ActualProduct)
</td>
<td>
#Html.DisplayFor(x => x.Cost)
#Html.HiddenFor(x => x.Cost)
</td>
<td>
#Html.TextBoxFor(x => x.DMarkup)
</td>
<td>
#Html.TextBoxFor(x => x.DSell)
</td>
<td>
#Html.TextBoxFor(x => x.RMarkup)
</td>
<td>
#Html.TextBoxFor(x => x.RSell)
</td>
<td>
#Html.DisplayFor(x => x.DateUpdated)
#Html.HiddenFor(x => x.DateUpdated)
</td>
<td>
<button type="submit">Update</button>
</td>
</tr>
}
Controllers
After updating in database, you cannot return View("Index", model);. Index view is expecting an enumerable. The best approach is to redirect to Index page again.
public class HomeController : Controller
{
public ActionResult Index()
{
List<OPISPriceReportOLY_Result> results = new List<OPISPriceReportOLY_Result>();
results.Add(new OPISPriceReportOLY_Result { cpid = 1 });
results.Add(new OPISPriceReportOLY_Result { cpid = 2 });
results.Add(new OPISPriceReportOLY_Result { cpid = 3 });
return View(results);
}
[HttpPost]
public ActionResult Update(OPISPriceReportOLY_Result model)
{
if (ModelState.IsValid)
{
int id = model.orpid;
using (var context = new IntranetCoreEntities())
{
var selected = context.OPISRetailPricings.Find(id);
selected.DMarkup = model.DMarkup;
selected.DSell = model.DSell;
selected.RMarkup = model.RMarkup;
selected.RSell = model.RSell;
context.SaveChanges();
}
}
return RedirectToAction("Index");
}
}
I am developping a ASP MVC project using Stored Procedures (Without Entity Framework).
After setting data in a formulaire, I want to show only the last record and not getting all the data from my database.
I know that I can write another method that select only the last record but I wonder if there is a solution to retrieve that from the view.
This is what I ve tried :
#for (var i = 0; i < 1; i++) {
#foreach (var item in Model)
{
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.LastName)
</th>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Phone)
</th>
<td>
#Html.DisplayFor(modelItem => item.Phone)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<td>
#Html.DisplayFor(modelItem => item.Date.Date)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Time)
</th>
<td>
#Html.DisplayFor(modelItem => item.Time)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Nbre_P)
</th>
<td>
#Html.DisplayFor(modelItem => item.Nbre_P)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Items)
</th>
<td>
#Html.DisplayFor(modelItem => item.Items)
</td>
</tr>
} }
The Model Bestellung.cs :
public class Bestellung
{
public int BestellungId { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
public string Time { get; set; }
public int Nbre_P { get; set; }
public string Items { get; set; }
[Display(Name = "Phone Number")]
[DataType(DataType.PhoneNumber)]
[Required(ErrorMessage = "Phone is required.")]
[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered phone format is not valid.")]
public String Phone { get; set; }
[Display(Name = "Email")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
[Required(ErrorMessage = "Email is required.")]
[DataType(DataType.EmailAddress)]
[StringLength(30)]
public string Email { get; set; }
[Display(Name = "First Name")]
[Required(ErrorMessage = "First name is required.")]
[StringLength(30)]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[Required(ErrorMessage = "Last name is required.")]
[StringLength(30)]
public string LastName { get; set; }
[Display(Name = "Address")]
[Required(ErrorMessage = "Address is required.")]
[StringLength(30)]
public string Address { get; set; }
}
One possible solution is to change:
#foreach (var item in Model)
to:
#foreach (var item in Model.Reverse().Take(1))
This still keeps the loop structure (i.e. the foreach), but ensures it will only ever process the last item in the original Model.
Considering your Model is of IEnumerable<T> type not sure why can't you just use LINQ Last() method which returns the last element
You don't want to do that.
If you filter it in the view, which is possible but I wouldn't recommend it, you habe the whole list model items loaded. Why would you even want to do it?
It's the task of the controller to filter your data and ONLY send the needed items.
In the controller call
Model.LastOrDefault();
If you want to show only the last record and not getting all the data from my database.
you can use this :
in controller :
var Bestellung = db.Bestellungs.OrderByDescending(p => p.BestellungId ).FirstOrDefault();
will get you the very last record from a Bestellungs
try this.No need to iterate any loop
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
<td>
#Html.DisplayFor(modelItem => Model.LastOrDefault().FirstName)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.LastName)
</th>
<td>
#Html.DisplayFor(modelItem => Model.LastOrDefault().LastName)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<td>
#Html.DisplayFor(modelItem => Model.LastOrDefault().Address)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<td>
#Html.DisplayFor(modelItem => Model.LastOrDefault().Email)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Phone)
</th>
<td>
#Html.DisplayFor(modelItem => Model.LastOrDefault().Phone)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<td>
#Html.DisplayFor(modelItem => Model.LastOrDefault().Date.Date)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Time)
</th>
<td>
#Html.DisplayFor(modelItem => Model.LastOrDefault().Time)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Nbre_P)
</th>
<td>
#Html.DisplayFor(modelItem => Model.LastOrDefault().Nbre_P)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.Items)
</th>
<td>
#Html.DisplayFor(modelItem => Model.LastOrDefault().Items)
</td>
</tr>
Your model should be list of modelobject not only model
Better to store your object in list of objects like that
class viewmodel
{
public list<yourclassname> propertyname;
}
and used this viewmodel class in view page
#foreach(var item in Model.PropertyName.lastordefault())
I would like to calculate the total of a db column (Amount) and display it on a label next to the total label in the view. I am unsure how to do carry out this particular task, should it be done in Javascript? or what other methods can I use?
This is my project...
MODEL
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace webassignment.Models
{
public class Donation
{
public int ID { get; set; }
public string DisplayName{ get; set; }
public DateTime Date { get; set; }
public decimal Amount { get; set; }
public decimal TaxBonus { get; set; }
public string Comment { get; set; }
}
public class DonationDBContext: DbContext
{
public DbSet<Donation> Donation { get; set; }
}
}
INDEX
// GET: Donations
public ActionResult Index()
{
return View(db.Donation.ToList());
}
INDEX VIEW
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.DisplayName)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<th>
#Html.DisplayNameFor(model => model.Amount)
</th>
<th>
#Html.DisplayNameFor(model => model.TaxBonus)
</th>
<th>
#Html.DisplayNameFor(model => model.Comment)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.DisplayName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Amount)
</td>
<td>
#Html.DisplayFor(modelItem => item.TaxBonus)
</td>
<td>
#Html.DisplayFor(modelItem => item.Comment)
</td>
<td>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
<script type="text/javascript">
You can do that in View, but better way would be to create a ViewModel, i am giving you basic idea how you can do it in View for time being :
#{
int totalAmount;
if(Model !=null)
{
totalAmount = Model.Sum(x=>x.Amount);
}
}
and down display it in html where ever you want:
<h1>#totalAmount</h1>
It appears that you are passing to the razor view a List of Donations so you should be able to use the extension methods for collections like model.Sum(x=> x.Amount) within your display.