7 days to go to mvc-ASP. 2nd Day

Source: Internet
Author: User

0. Preface

I believe that you have successfully completed the 1th Day course on the 2nd day of your study.

Let's review the main points of concern for the 1th day:

    • Why is ASP. NET MVC selected?

    • Comparison of ASP. NET Webforms and ASP.

    • Understanding the Controller and views of ASP.

Reminder: If you haven't finished your 1th day, it's a good idea to make sure you finish it. Our goal is to create a small MVC project on the last day with best practices and the latest techniques. Every day in Lab training, we add some functionality that is more practical than the previous day, which looks more perfect than the previous program.

1. Controller transmits data to View

In Lab 2, the creation of View is biased to static. In a real-world scenario, however, the View is usually presented with some dynamic data. In the next Lab, we'll show how the data is presented dynamically in View.

View will get the data shown in Model format from the Controller.

Model

in ASP. NET MVC, the Model shows the business data.

Lab 3-Using ViewData

ViewData is a dictionary that stores the data that the Controller transmits to the View. The Controller adds an entry to the ViewData dictionary and the View reads from the dictionary. Now let's start with a Demo.

First step: Create a Model class

Under the Model folder, create a new class named Employee.

public class Employee{    public string FirstName { get; set; }    public string LastName { get; set; }    public int Salary { get; set; }}

Step two: Get the Model from the Controller

Create an Employee object in the GetView method.

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

Note: Make sure the Model is introduced using the using statement in your class, or you will use the full name of the Employee class when you write your program.

using WebApplication1.Models;

Step three: Create ViewData and return to View

Stores the Employee object in ViewData.

ViewData["Employee"] = emp;return View("MyView");

Fourth step: Show Employee data in View

Open the file myview.cshtml. Retrieve Employee data from ViewData and show it.

<div>    @{        WebApplication1.Models.Employee emp =     (WebApplication1.Models.Employee)ViewData["Employee"];    }    <b>Employee Details </b><br/>    Employee Name : @[email protected] <br/>    Employee Salary: @emp.Salary.ToString("C")</div>

Fifth step: Test output

Press F5 to test the application.

Lab 3 's Q&a

What is the difference between using curly braces "{" and "}" and not using curly braces while writing Razor code?

In Lab 3, @emp. FirstName can be replaced with the following code.

@{    Response.Write(emp.FirstName);}

If you don't use curly braces after @, it's just to show the value of a variable or expression.

Why do I need to cast?

Some objects are hosted inside the ViewData. Each time a new value is added, it is converted to the Object type.

Therefore, each time a cast is required to get the value of the object.

"@emp. FirstName @emp. What is the meaning of lastname"?

This means that the LastName is displayed after the FirstName and is separated by a space.

If you just want to use a @ keyword, can you do just that?

The answer is yes. Through the syntax @ (EMP. Firstname+ "" +emp. LastName).

Why do I want to hardcode the Employee class in the Controller class?

This is just to show the demo. In fact, we will get the data in the database, WCF, Web Service, or anywhere else.

What is database logic, data access layer, and business layer?

    • The data access layer is a layer that is not displayed in ASP. In fact, it always exists, but it has never been included in the definition of MVC.

    • The business layer, as explained earlier, is part of the Model.

A complete MVC structure.

Lab 4-Using ViewBag

ViewBag is like ViewData's grammatical honey. ViewBag uses the dynamic features of C # 4.0 to make ViewData dynamic.

ViewBag internal use of ViewData.

First step: Create a View Bag

Continue with Lab 3 and replace the third step in Lab 3 with the following code snippet:

ViewBag.Employee = emp;

Step two: Show EmployeeData in View

Replace the fourth step in Lab3 with the following code snippet:

@{    WebApplication1.Models.Employee emp =         (WebApplication1.Models.Employee)ViewBag.Employee;}Employee DetailsEmployee Name: @emp.FirstName @emp.LastName Employee Salary: @emp.Salary.ToString("C")

Step three: Test and output

Press F5 and test the application.

Lab 4 's Q&a

Can we transfer ViewData and get it in ViewBag form?

The answer is yes. The reverse is also possible. As I mentioned before, ViewBag is just a ViewData of the syntax of honey.

The problems of ViewData and ViewBag

ViewData and ViewBag are a great way to choose between Controller and View transfer data. But in actual project applications, none of them is the best way to practice. Now let's discuss the disadvantages of using ViewData and ViewBag.

Performance issues

The data type in ViewData is Object. So we need to do the right type conversion before we use it. This operation poses an additional burden on performance.

There is no type safety and there is no compile-time error.

If we try to convert the type to the wrong type, or if we use the wrong Key value when retrieving the value of the object, we will have an error at run time. But for a good programming practice, errors should be captured at compile time.

There is no correct connection between data transfer and reception

As a developer, I personally think this is a major problem.

In MVC, the connection between the Controller and the View is weak, loosely connected.

The controller doesn't care about what's happening in the view, and the view doesn't really care what happens in the controller.

From the Controller we can transfer one or more ViewData or ViewBag values. Now, when a developer wants to write a View, he needs to remember what the Controller is going to transfer. If a Controller developer is not the same person as the View developer, the situation will become more difficult. Because it is completely unconcerned, this will lead to inefficiencies in the development process and may also cause running errors.

Lab 5-Understanding strongly typed views

Just now the above three points about ViewData and ViewBag can be attributed to data types. The data type stored in ViewData is "object".

If, in some way, we were able to set the data type for the data transferred in the Controller and View, then the problem would be solved, and that would be strongly typed views.

Now let's do a Demo. This time we will be raising the View to the next level. If the salary is more than 15000, then the yellow color is displayed, otherwise the green color.

First step: Create a strongly typed View

Add the following code to the top of the View:

@model WebApplication1.Models.Employee

Based on this statement, our view is made into a strongly typed view of Employee type.

Step two: Show the data

Now, in View, just using the @Model and Dot (.) operation, you can intelligently get the Model, which is all the data values of Empolyee.

Write down the following code to show the data:

Employee DetailsEmployee Name : @Model.FirstName @Model.LastName @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>}

Step three: Transfer Model data from the Controller's Action method

Change the Action method to the following code snippet:

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

Fourth step: Test and output

Lab 5 's Q&a

Do you need to use the full name of the class for each type declaration in View, that is, Namespace.ClassName?

The answer is in the negative. We can use the "using" statement.

@using WebApplication1.Models@model Employee

Do we have to always use a strongly typed view, or can we occasionally use ViewData or ViewBag?

If you want to practice the best way, it's best to use strongly typed views.

Can we use more than one Model type for view of a strongly typed view?

The answer is in the negative. In real-world projects, when we want to show multiple Model in one view, we often end up at this point. The solution to this requirement is discussed in the next section.

2. Understanding the View Model in ASP.

In Lab 5, we have violated the MVC guidelines. According to MVC, V represents a purely UI. It should not contain any logic. We have violated MVC's structural rules by the following three points:

    • First name and last name are appended, and the full name is displayed with them. This is a logical operation.

    • The Salary is presented in monetary form. This is a logical operation.

    • Shows the different colors of different wages. These simple operations based on different values change the appearance of HTML elements. This is a logical operation.

In addition to the above three points, there is a more interesting point to discuss.

In this case, we want to show different types of data in View. For example: Displays the currently logged on user name and employee data.

We can use the following two ways to achieve this problem:

    1. Add a UserName property to the Employee class. Every time we want to show a new data in the view, we add an attribute to the Employee class. This seems unreasonable, and this attribute may not be associated with Employee. This also violates SOLID's SRP guidelines.

    2. Use ViewBag or ViewData. We have discussed the drawbacks of this method just now.

ViewModel Solutions

ViewModel is a layer that is not declared in an ASP. NET MVC application. It fits between Model and view and is a data container for view.

What is the difference between Model and ViewModel?

Model refers specifically to business data. It is created based on business and data structures. ViewModel refers to View data. It is created based on the views view.

How does the ViewModel work?

The working principle is very simple.

    • The Controller handles the user's interaction logic, or simply, processes the user request.

    • Controller obtains one or more Model data.

    • The Controller decides which View will respond correctly to the request.

    • The Controller will create and initialize the ViewModel object from the received Model data according to the view's requirements.

    • The Controller will transmit ViewModel data to view in the form of a viewdata/viewbag/strongly typed view.

    • The Controller will return to View.

How will View and ViewModel be correlated?

The view will be a ViewModel-strong type.

How will Model and ViewModel be correlated?

Model and ViewModel should be independent of each other. The Controller will create and initialize the ViewModel object based on one or more Model objects.

Let's do a little Lab to get a better understanding of it.

3. Lab 6-Implementing View Model

First step: Create a Folder

Name a folder in your project named ViewModels.

Step Two: Create Employeeviewmodel

To do this, let's take a look at all of the View's requirements first.

    1. First Name and LastName need to be merged, so they should be merged before the presentation.

    2. Use the currency form to display the Amount.

    3. Different Salary show different colors.

    4. The current User Name is also displayed in the view.

Create a Employeeviewmodel class under the ViewModels folder, as follows:

public class EmployeeViewModel{    public string EmployeeName { get; set; }    public string Salary { get; set; }    public string SalaryColor { get; set; }    public string UserName{get;set;}}

It is important to note that in this ViewModel class, FirstName and LastName are replaced by an attribute, that is, EmployeeName. And the Salary data type is String, in addition to this, added two properties, namely Salarycolor and UserName.

Step three: Using ViewModel in View

In Lab 5, we have the View strongly typed as Employee. It is now strongly typed as Employeeviewmodel.

@using WebApplication1.ViewModels@model EmployeeViewModel

Fourth Step: Display the data in View.

Replace the contents of the View with the following code snippet:

Hello @Model.UserName

Fifth step: Create and Transfer ViewModel

In the GetView action method, obtain the Model data and convert it to a 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);}

Sixth step: Test and output

Press F5 and test the output.

The result of the output is the same as in Lab 5, but no logic is included in this View.

Lab 6 's Q&a

Does this mean that every Model will have a ViewModel?

The answer is in the negative. In fact, every View will have a ViewModel.

Is there some correlation between Model and ViewModel a good practice?

The answer is in the negative. As a best practice, Model and ViewModel should be independent, not associative, between each other.

Do we need to always create ViewModel? What if view does not contain any presentation logic and the view only shows the Model's data?

We should always create ViewModel. Each View should have its own ViewModel, even if the properties of the ViewModel are exactly the same as those of the Model.

Suppose a scenario where View does not contain presentation logic and uses Model data instead of ViewModel.

The problem is that if there is a need to add new data to the UI, or to demonstrate the need for logic, then we need to re-plan a UI.

So it's best that we create ViewModel at the outset to prevent demand from increasing. In this case, the initial phase of the ViewModel is almost identical to the Model.

4. Using Collection in Lab 7-view

In this section of Lab, we'll show a list of Employees in View.

First step: Change the Employeeviewmodel class

Removes the UserName property from the Employeeviewmodel class.

public class EmployeeViewModel{    public string EmployeeName { get; set; }    public string Salary { get; set; }    public string SalaryColor { get; set; }}

Step Two: Create a collection

Under the ViewModel folder, create a class that is named Employeelistviewmodel.

public class EmployeeListViewModel{    public List<EmployeeViewModel> Employees { get; set; }    public string UserName { get; set; }}   

Step three: Change the strong type of View

Replace the strong type of the myview.cshtml with the Employeelistviewmodel.

@using WebApplication1.ViewModels@model EmployeeListViewModel

Fourth Step: Display all employee information in View.

<body>    Hello @Model.UserName    

Fifth step: Create a business Layer for Employee

In this Lab, we will upgrade our project to a new level. We will add a business Layer to the project. Create a new folder in the project named Businesslayer, and then create a new class named Employeebusinesslayer, which contains a method named 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; }}

Sixth step: data transfer 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);}

Seventh step: Execute and test the output

Press F5 to perform the application.

Lab 7 's Q&a

Can we set the mandatory type of the view to List?

The answer is yes. We can.

Why do we create a separate class, Employeelistviewmodel, why don't we use a strongly typed view of list< Employeelistviewmodel >?

If we use the List directly, instead of using the Employeelistviewmodel class, it can cause two problems.

    1. There may be a need for display logic in the future.

    2. The UserName property. Because UserName and Employees are not related. It is associated with a complete View.

Why should we remove the UserName attribute from Employeeviewmodel and then use it as part of the Employeelistviewmodel?

UserName is the same for all employees, and if you leave the properties of UserName in Employeeviewmodel, you add redundant code and additional memory space to increase the data.

5. Conclusion

We have completed the 2nd day of MVC learning. On the 3rd day we will make the project into the next phase.

Let me enjoy the study together!

Original address: Learn MVC Project in 7 days

7 days to go to mvc-ASP. 1th Day

This article is compiled and collated by OneAPM engineers. OneAPM is the emerging leader in China's basic software industry, helping enterprise users and developers easily implement slow program code and real-time crawling of SQL statements. To read more technical articles, please visit the OneAPM official blog.

7 days to go to mvc-ASP. 2nd Day

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.