asp.net mvc tutorial for beginners
Lección 119 de 496 · Part 29 Using data transfer object as the model in mvc · Bases de datos
Part 29 Using data transfer object as the model in mvc
In this video we will discuss, using data transfer object as the model in mvc. Please watch Part 28, before proceeding.
Let’s say the business requirement is such that, we want to display total number of employees by department. At the moment, either the Employee or Department class does not have Total property. This is one example, where a Data Transfer Object can be used as a model.
Right click on the “Models” folder and add a class with name=”DepartmentTotals.cs”. Copy and paste the following code.
public class DepartmentTotals
{
public string Name { get; set; }
public int Total { get; set; }
}
Now add the following “EmployeesByDepartment” controller action method to EmployeeController class.
public ActionResult EmployeesByDepartment()
{
var departmentTotals = db.Employees.Include(“Department”)
.GroupBy(x =] x.Department.Name)
.Select(y =] new DepartmentTotals
{
Name = y.Key, Total = y.Count()
}).ToList();
return View(departmentTotals);
}
At this point, build the solution, so that the newly added DepartmentTotals class is compiled.
Now right click on “EmployeesByDepartment” action method in “EmployeeController” and select “Add View” from the context menu.
View name = EmployeesByDepartment
View engine = Razor
Select “Create a strongly-typed view” checkbox
Model class = DepartmentTotals
Model class = DepartmentTotals
To list the employees in ascending order of total employee, use OrderBy() LINQ method as shown below.
var departmentTotals = db.Employees.Include(“Department”)
.GroupBy(x =] x.Department.Name)
.Select(y =] new DepartmentTotals
{
Name = y.Key, Total = y.Count()
}).ToList().OrderBy(y =] y.Total);
To sort the list in descending order use, OrderByDescending() LINQ method.
var departmentTotals = db.Employees.Include(“Department”)
.GroupBy(x =] x.Department.Name)
.Select(y =] new DepartmentTotals
{
Name = y.Key, Total = y.Count()
}).ToList().OrderByDescending(y =] y.Total);
return View(departmentTotals);
Text version of the video
http://csharp-video-tutorials.blogspot.com/2013/06/part-29-using-data-transfer-object-as.html
Slides
http://csharp-video-tutorials.blogspot.com/2013/09/part-29-using-data-transfer-object-as.html
All ASP .NET MVC Text Articles
http://csharp-video-tutorials.blogspot.com/p/aspnet-mvc-tutorial-for-beginners.html
All ASP .NET MVC Slides
http://csharp-video-tutorials.blogspot.com/p/aspnet-mvc-slides.html
All Dot Net and SQL Server Tutorials in English
https://www.youtube.com/user/kudvenkat/playlists?view=1&sort=dd
All Dot Net and SQL Server Tutorials in Arabic
https://www.youtube.com/c/KudvenkatArabic/playlists