ASP.Net MVC

champak
₹2,000.00 ₹300.00
  • 11 students
  • 6 lessons
  • 0 quizzes
  • 10 week duration

ASP.Net MVC

Passing Data from Controller to View. Introducing Razor

Passing Data from Controller to View

Now it’s time to look at the third layer of MVC that is Model.

In ASP.NET MVC Model represents business data. Data from Controller to View will be passed in the form of Model. Understand Razor Before we proceed with the Lab first we have to understand the concept of Razor. In ASP.NET MVC file with “.cshtml” indicates Razor View.

Before MVC 5 we had two options to create View – ASPX and Razor. But with MVC 5 ASPX option is removed. Difference between Razor and ASPX is the way we write dynamic code in the View. Just like VB.NET and C# have different syntaxes, Razor and ASPX have different syntaxes too. In Razor dynamic code will be written between @{} and in ASPX it will be written between <% %>. Inside action method View function creates ViewResult. ViewResult then choose the correct ViewEngine (either Razor or ASPX View Engine) which understands the corresponding View syntaxes and creates final HTML.

Lab 3 – Using ViewData ViewData

is a dictionary, which contains data to be passed between Controller and Views. Controller will add items to this dictionary and View reads from the same.

Let’s do a demo.

Step 1 – Create Model

class Create a new class called Employee inside Model folder as follows:

[c#]

public class Employee

{

public string FirstName {get; set;}

public string LastName {get; set;}

public int Salary {get; set;}

}

[/c#]

Step 2 – Get Model in Controller

Create Employee object inside the “GetView” method as follows:

Employee emp = new Employee(); emp.FirstName = “Sukesh”; emp.LastName=”Marla”; emp.Salary = 20000;

 

Note: Make sure to put “using” statement in the top or else we have to put fully qualified name of the Employee. In my case it will be like below. using WebApplication1.Models;

Step 3 –

Create ViewData and return the View Store Employee object in ViewData as follows: ViewData[“Employee”] = emp; Return View(“MyView”);

Step 4 – Display Employee Data in View Open MyView.cshtml. Retrieve the Employee data from the ViewData & display it as follows:

[c#]

<div> @{ WebApplication1.Models.Employee emp=(WebApplication1.Models.Employee) ViewData[“Employee”];

}

<b>Employee Details </b><br /> Employee Name: @emp.FirstName@emp.LastName <br /> Employee Salary: @emp.Salary.ToString(“C”)

</div>

[/c#]

Step 5 – Test the output Press F5 and test the application.

 

 

 

Talk on Lab 3

What is the difference between writing Razor code with brace brackets (that is “{“ and “}”) and without brace brackets? @SomeExpression is termed as expression. It will simply display the value of expression on screen. @{…} is termed as scriptlets. It will be used when we want to write multiple executable statements. We can write any C# code between “@{“ and “}”. Why is casting required in case of ViewData? ViewData holds objects internally. Every time a new value is added into it, it gets boxed to object type. So unboxing is required every time we extract value out of it. What is the meaning of “@emp.FirstName @emp.LastName”? It means Display First Name followed by a space and then Last Name. Can we write same thing with single @ keyword? Yes, then syntax for this will be @(emp.FirstName+ “ “ +emp.LastName)

 

Why hardcoded Employee class is created in Controller?

Just for demo purpose. In real time we may get it from database, WCF (Windows Communication Foundation) or Web service or may be from somewhere else. Soon we will remove this hard coding. What about the Database Logic/ Data Access Layer? l Data Access Layer is one of the unspoken layers in ASP.NET MVC. It’s always there but never included in the MVC definition. l Business layer is considered as part of Model layer. For better code management in some projects it is created a as a separate layer. Note: Both of this above layers will be included into the project in one of the upcoming Labs. Right now just get a feel of MVC and move ahead.

 

☺ Complete MVC Structure

 

 

Lab 4 –

Using ViewBag ViewBag

is just a syntactic sugar for ViewData. ViewBag uses the dynamic feature of C# 4.0 and makes ViewData dynamic. ViewBag internally uses ViewData. Step 1 – Create ViewBag Continue with the same Lab 3 and replace Step 3 with following code snippet. ViewBag.Employee = emp;

Step 2 –

Display EmployeeData in View Change

Step 4

with following code snippet:

[c#]

@{ WebApplication1.Models.Employee emp = (WebApplication1.Models.Employee) ViewBag.Employee; } <b>Employee Details</b><br /> Employee Name: @emp.FirstName @emp.LastName <br /> Employee Salary: @emp.Salary.ToString(“C”)

[/c#]

Step 3 – Test the output Press F5 and test the application.

 

 

Talk on Lab 4

Can we pass ViewData and get it as ViewBag? Yes, we can. Vice-versa is also possible. As I said before, ViewBag is just a syntactic sugar for ViewData. Problems with ViewData and ViewBag ViewData and ViewBag both are good option for passing values between Controller and View. But in real time projects it’s not a good practice to use any of them. Let’s discuss couple of disadvantages of using ViewData and ViewBag. Performance issues Values inside the ViewData are of type Object. We have to cast the value to correct type before using it. It adds additional overhead on performance. No Type safety and no compile time errors

If we try to cast values to wrong type or if we use wrong keys while retrieving the values, we will get runtime error. As a good programming practice, error should be tackled at compiled time. No Proper connection between Data sent and Data Received As a developer I personally found this as a major issue. In MVC, Controller and View are loosely connected to each other. Controller is completely unaware about what’s happening in View and View is unaware about what’s happening in Controller. From Controller we can pass one or more ViewData/ViewBag values. Now when developer creates a View, he/she has to remember what is coming from the Controller. If Controller developer is different from View developer then it becomes even more difficult. It leads to many runtime issues and inefficiency in development. Lab 5 – Understand strongly typed Views Reason for all three problems of ViewData and ViewBag is the data type. Data type of values inside ViewData is of type “Object”. Somehow if we are able to fix the type of data which needs to be passed between Controller and View the boxing unboxing problem will get solved. This is where strongly typed Views come to rescue. Let’s do a demo of the same. This time we will take our View requirement to next level. If salary is greater than 15000 then it will be displayed in yellow color else green color.

Step 1 –

Make View a strongly typed View Add following statement at the top of the View: @Model WebApplication1.Models.Employee Above statement make our View a strongly typed View of type Employee. Step 2 – Display Data Now inside View simply type @Model and Dot (.) and in Intellisense you will get all the properties of Model (employee) class.

Write down following code to display the data:

[c#]

<b>Employee Details</b><br /> Employee Name: @Model.FirstName @Model.LastName <br /> @if(Model.Salary>15000) { <span style=”background- color:yellow”> Employee Salary: @Model.Salary.ToString(“C”) </span> } else { <span style=”background-color:green”> Employee Salary: @Model.Salary.ToString(“C”) </span> }

[/c#]

 

 

Step 3 –

Pass Model data from Controller Action method Change the code in the action method to following:

Employee emp = new Employee(); emp.FirstName = “Sukesh”; emp.LastName=”Marla”; emp.Salary = 20000; return View(“MyView”, emp);

Step 4 – Test the output

 

 

Talk on Lab 5

Is it required to type fully qualified class Name (Namespace.ClassName) in View every time? No, we can put a “using” statement. @using WebApplication1.Models @Model Employee Is it must to make View a strongly typed View always or can we go with ViewData or ViewBag sometimes? As a best practice always make Views a strongly typed View. Can we make our View a strongly typed View of more than one Model? No, we can’t. In real time project we often end up at a point where we want to display multiple Models in one View. Solution for this requirement will be discussed in next Lab. Understand View Model in ASP.NET MVC In Lab 5 we have violated MVC principle. According to MVC, V that is View should be pure UI. It should not contain any kind of logic. We have done following three things which purely violates MVC architecture rules:

 

l Append First name and Last Name and Display it as Full Name – Logic l Display Salary with Currency – Logic l Display Salary in different color based on value. In simple words change appearance of HTML element based on some value. – Logic Other than these three issues, there is one more point worth discussion. Let’s say we have situation where we want to display more than one kind of data in the View. For example, showing current logged Users Name along with Employee data. We can implement this concept in one of the following ways. 1. Add UserName property to Employee class – Every time we want to display new data in the View, adding new property to employee class seems illogical. This new property may or may not be related to Employee. 2. Use ViewBag or ViewData – We already discussed problems of using this approach. ViewModel – A Solution ViewModel is one of the unspoken layers in the ASP.NET MVC application. It fits between Model and View and act as data Container for View.

Difference between Model and ViewModel? Model is business specific data. It will be created based on business and database structure. ViewModel is View specific data. It will be created based on the View. How it works exactly? It’s simple. l Controller handles user interaction logic or in simple words, handles the user’s requests. l Controller gets one or More Model data. l Controller will decide which View suits best as response for the correct request. l Controller will create and initialize ViewModel object from Model data retrieved based on View requirement. l Controller will pass ViewModel data to View by means of ViewData/ViewBag/strongly typed View. l Controller will return the View. How View and ViewModel will be connected here? View is going to be a strongly typed View of type ViewModel. How Model and ViewModel will be connected? Model and ViewModel should be independent of each other. Controller will create and initialize ViewModel object based on one or more Model object. Let’s do a small Lab to understand it better.

Lab 6 – Implementing View Model Step 1 – Create Folder

Create a new folder in the project and call it ViewModels.

Step 2 – Create EmployeeViewModel In order to do that, let’s list all the requirement for the View: 1. First Name and Last Name should be combined before displaying. 2. Amount should be displayed with currency. 3. Salary should be displayed in different color (based on value). 4. Current User Name should also be displayed in the View as well. Create a new class called EmployeeViewModel inside ViewModels folder will look as shown below. public class EmployeeViewModel { public string EmployeeName {get; set;} public string Salary {get; set;} public string SalaryColor {get; set;} public string UserName{get;set;} }

Please note, in ViewModel class, FirstName and LastName properties are replaced with one single property called EmployeeName, Data type of Salary property is string and two new properties are added called SalaryColor and UserName. In easy words, ViewModel will be created based on View.

Step 3 –

Use View Model in View In Lab 5 we had made our View a strongly type View of type Employee. Change it to EmployeeViewModel. @using WebApplication1.ViewModels @Model EmployeeViewModel

Step 4

Display Data in the View Replace the contents in View section with following snippet: Hello @Model.UserName <hr /> <div> <b>Employee Details</b><br /> Employee Name: @Model.EmployeeName <br /> <span style=”background-color:@Model.SalaryColor”> Employee Salary: @Model.Salary </span> </div>

 

Step 5 –

Create and Pass ViewModel In GetView action method, get the Model data and convert it to ViewModel object as follows: public ActionResult GetView() { Employee emp = new Employee();

emp.FirstName = “Sukesh”; emp.LastName=”Marla”; emp.Salary = 20000; EmployeeViewModel vmEmp = new EmployeeViewModel(); vmEmp.EmployeeName = emp.FirstName + “ “ + emp.LastName; vmEmp.Salary = emp.Salary.ToString(“C”); if(emp.Salary>15000) { vmEmp.SalaryColor=”yellow”; } else { vmEmp.SalaryColor = “green”; } vmEmp.UserName = “Admin” return View(“MyView”, vmEmp);}

 

Step 5 –

Test the output Press F5 and test the output. (Output looks same as displayed result in Lab 5 but this time View won’t contain any logic.)

 

Talk on Lab 6

Does it mean, every Model will have own ViewModel? No, every View will have its own ViewModel. There shouldn’t be any connection between Model and ViewModel. Is it a good practice to have some relationship between Model and ViewModel? No, as a best practice Model and ViewModel should be independent of each other. Is it required to create ViewModel for every View? Yes, as a best practice we should create one ViewModel for every View. Is it a good practice to use Model directly sometimes instead of ViewModel? Let’s say, we skip ViewModel creation in a scenario where View displays data specific to only one Model and won’t contain any presentation logic. Now the problem is handling change requirement. If some time in the future if we come up with a requirement of displaying new data in the UI, we won’t left with any choice than modifying existing Model or using ViewBag. So as a best practice, create ViewModel in the beginning only so that future changes will get tackled easily.

Lab 7–

View with Collection In this Lab we will display list of Employees in the View.

Step 1 –

Change EmployeeViewModel class Remove UserName property from EmployeeViewModel. public class EmployeeViewModel { public string EmployeeName {get; set;} public string Salary {get; set;} public string SalaryColor {get; set;} } Step 2 – Create Collection View Model Create a class called EmployeeListViewModel inside ViewModel folder as follows: public class EmployeeListViewModel { public List<EmployeeViewModel> Employees {get; set;} public string UserName {get; set;} }

Step 3

Change type of strongly typed View Make MyView.cshtml a strongly typed View of type EmployeeListViewModel. @using WebApplication1.ViewModels @Model EmployeeListViewModel Step 4– Display all employees in the View <body> Hello @Model.UserName <hr /> <div> <table> <tr> <th>Employee Name</th> <th>Salary</th> </tr> @foreach (EmployeeViewModel item in Model.Employees) { <tr> <td>@item.EmployeeName</td> <td style=”background-color:@item.SalaryColor”>@item.Salary</td> </tr> } </table> </div> </body>

Step 5 –

Create Business Layer for Employee In this Lab, we will take our project to next level. We will add Business Layer to our project.

Create a new class called EmployeeBusinessLayer inside Model folder with a method called GetEmployees. public class EmployeeBusinessLayer { public List<Employee> GetEmployees() { List<Employee> employees = new List<Employee>(); Employee emp = new Employee(); emp.FirstName = “johnson”; emp.LastName = “fernandes”; emp.Salary = 14000; employees.Add(emp); emp = new Employee(); emp.FirstName = “michael”; emp.LastName = “jackson”; emp.Salary = 16000; employees.Add(emp); emp = new Employee(); emp.FirstName = “robert”;

emp.LastName = “pattinson”; emp.Salary = 20000; employees.Add(emp); return employees; } } Step 6 – Pass data from Controller public ActionResult GetView() { EmployeeListViewModel employeeListViewModel = new EmployeeListViewModel(); EmployeeBusinessLayer empBal = new EmployeeBusinessLayer(); List<Employee> employees = empBal.GetEmployees(); List<EmployeeViewModel> empViewModels = new List<EmployeeViewModel>(); foreach (Employee emp in employees) { EmployeeViewModel empViewModel = new EmployeeViewModel(); empViewModel.EmployeeName = emp.FirstName + “ “ + emp.LastName; empViewModel.Salary = emp.Salary.ToString(“C”);

if (emp.Salary > 15000) { empViewModel.SalaryColor = “yellow”; } else

 

{ empViewModel.SalaryColor = “green”; } empViewModels.Add(empViewModel); } employeeListViewModel.Employees = empViewModels; employeeListViewModel.UserName = “Admin”; return View(“MyView”, employeeListViewModel); } Step 7 – Execute and Test the Output Press F5 and execute the application.

 

Talk on Lab 7

Can we make View a strongly typed View of List<EmployeeViewModel>? Yes, we can. Why we created a separate class called EmployeeListViewModel, why didn’t we make View a strongly typed View of type List<EmployeeViewModel>? If we use List<EmployeeViewModel> directly instead of EmployeeListViewModel then there will be two problems. 1. Managing future presentation logic. 2. Secondly UserName property. UserName is not associated with individual employees. It is associated with complete View. Why is UserName included in EmployeeListViewModel instead of EmployeeViewModel? UserName is going to be same for all the employees. Keeping UserName property inside EmployeeViewModel just increases the redundant code and also increases the overall memory requirement for data.

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *