7-day experience ASP. net mvc-2nd days, asp. netmvc

Source: Internet
Author: User

7-day experience ASP. net mvc-2nd days, asp. netmvc
0. Preface

I believe that you have successfully completed the course for the first 2nd days.

Let's take a look back at the main points of interest in the 1st day:

  • Why ASP. net mvc?

  • Comparison between ASP. NET Webforms and ASP. NET MVC

  • Understanding ASP. net mvc Controller and Views

Note: If you have not completed the course for the last 1st days, you are advised to finish it first. Our goal is to create a small MVC project with best practices and the latest technical methods on the last day. During Lab training every day, we will add some practical functions than the previous day, which looks more perfect than the previous program.

1. The Controller transmits data to the View.

In Lab 2, View creation is static. However, in real scenarios, View usually displays some dynamic data. In the next Lab, we will show how the View dynamically displays data.

View obtains the data displayed in Model format from the Controller.

Model

In ASP. net mvc, Model displays business data.

Lab 3-use ViewData

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

Step 1: create a Model class

Create a new class in the Model folder and name it "Employee.

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

Step 2: Obtain 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 you use the Using statement in the class to introduce the Model. Otherwise, you must use the full name of the Employee class when writing the program.

using WebApplication1.Models;

Step 3: Create ViewData and return to View

Store the Employee object in ViewData.

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

Step 4: display the Employee data in the View

Open the MyView. cshtml file. Retrieve and display the Employee data from ViewData.

<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>

Step 5: test the output

Press F5 to test the application.

Q & A of Lab 3

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

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

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

If no curly brackets are used after @, it is only used to display the values of variables or expressions.

Why is forced conversion required?

ViewData contains some objects. Each time a new value is added, it is converted to the Object type.

Therefore, you need to forcibly convert each time to obtain the object value.

What does "@ emp. FirstName @ emp. LastName" mean?

This means that LastName is displayed after FirstName and separated by spaces.

If you only want to use one @ keyword, can you achieve the result just now?

The answer is yes. Use the syntax @ (emp. FirstName + "+ emp. LastName ).

Why do we need to hard encode the Employee class in the Controller class?

This is only for demo demonstration. In fact, we will obtain data in databases, WCF, Web services, or other places.

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

  • The data access layer is not displayed in ASP. net mvc. In fact, it always exists, but it is never included in the MVC definition.

  • As previously explained, the business layer is part of the Model.

Complete MVC structure.

Lab 4-use ViewBag

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

ViewBag uses ViewData internally.

Step 1: Create View Bag

Proceed to Lab 3 and replace step 3 in Lab 3 with the following code snippet:

ViewBag.Employee = emp;

Step 2: Display EmployeeData in View

Replace Step 4 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 3: Test and Output

Press F5 and test the application.

Q & A of Lab 4

Can we transmit ViewData and obtain it in the form of ViewBag?

The answer is yes. This is also possible. As I mentioned earlier, ViewBag is only the syntactic honey of ViewData.

ViewData and ViewBag Problems

ViewData and ViewBag are good methods for data transmission between the Controller and View. However, in actual project applications, none of them is the best practice. Now let's discuss the disadvantages of using ViewData and ViewBag.

Performance problems

The data type in ViewData is Object. Therefore, we need to perform correct type conversion before use. This operation puts extra burden on performance.

No type security or compilation errors.

If we try to convert the type to the wrong type, or we use the wrong Key value when retrieving the object value, we will encounter an error at runtime. But for a good programming practice, errors should be captured during compilation.

There is no correct connection between data transmission and data reception

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

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

The Controller does not care about what happened in the View. Similarly, the View does not care about what happened in the Controller.

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

Lab 5-understand strong-type Views

The three questions about ViewData and ViewBag mentioned above can be attributed to the data type. The data type stored in ViewData is "Object 」.

If, in some way, we can set the data type for the data transmitted in the Controller and View, the problem will be solved, and this method is a strong type of Views.

Now let's make a Demo. This time, we will upgrade the View requirement to the next level. If the salary is higher than 15000, it will be yellow; otherwise, it will be green.

Step 1: create a strong View

Add the following code to the top of the View:

@model WebApplication1.Models.Employee

Based on this statement, our View becomes a strongly typed View with the type of Employee.

Step 2: Display Data

Now, in the View, only @ Model and Dot (.) operations can be used to intelligently obtain all the data values of the Model, that is, Empolyee.

Write the following code to display the data:

Employee DetailsEmployee Name : @Model.FirstName @Model.LastName @if(Model.Salary>15000){    <span >    Employee Salary: @Model.Salary.ToString("C")    </span>}else{               <span >    Employee Salary: @Model.Salary.ToString("C")        </span>}

Step 3: transmit 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);

Step 4: Test and Output

Q & A of Lab 5

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

The answer is no. We can use the "using" statement.

@using WebApplication1.Models@model Employee

Must we always use a strong-type view, or can we occasionally use ViewData or ViewBag?

If you want to use the best method, you 'd better use the strong type view.

Can we use multiple Model types for views of strong-type views?

The answer is no. In actual projects, when we want to display multiple models in a view, we often end with this. The solution to this requirement will be discussed in the next section.

2. Understand the View Model in ASP. NET MVC

In Lab 5, we have violated the MVC principles. According to MVC, V represents a pure UI. It should not contain any logic. We have violated the MVC structure rules through the following three points:

  • First Name and Last Name are appended, and they are used to display the full Name. This is a logical operation.

  • Salary is displayed in currency form. This is a logical operation.

  • Shows the different colors of different salaries. 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 another question worth discussing.

In this case, we want to display different types of data in the View. For example, the user name and employee data of the current logon are displayed.

We can use the following two methods to solve this problem:

ViewModel Solution

ViewModel is a layer not declared in ASP. net mvc applications. It is applicable between Model and View and serves as a data container for View.

What is the difference between Model and ViewModel?

Model refers to business data. It is created based on the business and data structure. ViewModel refers to View data. It is created based on The View.

How does ViewModel work?

The working principle is very simple.

  • The Controller processes the interaction logic of users, or, simply put, processes user requests.

  • The Controller obtains one or more Model data.

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

  • The Controller creates and initializes the ViewModel object from the received Model data according to the view requirements.

  • The Controller transmits the ViewModel data to the View in ViewData/ViewBag/strong View mode.

  • The Controller returns the View.

How will View and ViewModel be associated?

View is a View with a ViewModel as a strong type.

How will Model and ViewModel be associated?

Model and ViewModel should be independent of each other. The Controller creates and initializes a ViewModel object based on one or more Model objects.

Let's make a small Lab to better understand it.

3. Lab 6-View Model implementation

Step 1: Create a folder

Name a folder in the project and name it ViewModels.

Step 2: Create the EmployeeViewModel

To do this, let's clarify all the requirements of the View.

Create an EmployeeViewModel class in the ViewModels folder, 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;}}

In this ViewModel class, FirstName and LastName are replaced by an attribute, namely, EmployeeName. The data type of Salary is String. In addition, two attributes are added, namely SalaryColor and UserName.

Step 3: Use ViewModel in View

In Lab 5, we set the strong View type to Employee. Now, set the strong type to EmployeeViewModel.

@using WebApplication1.ViewModels@model EmployeeViewModel

Step 4: display data in the View.

Use the following code snippet to replace the content in the View:

Hello @Model.UserName

Step 5: Create and transmit ViewModel

In the GetView action method, obtain the Model data and convert it to a ViewModel object, as shown below:

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 6: Test and Output

Press F5 and test the output.

The output result is the same as that of Lab 5, but this View does not contain any logic.

Q & A of Lab 6

Does this mean that every Model has a ViewModel?

The answer is no. In fact, every View has a ViewModel.

Is it a good practice to associate Model with ViewModel?

The answer is no. As a best practice, Model and ViewModel should be independent of each other, rather than associated.

Do we always need to create ViewModel? What if the View does not contain any display logic and the View only displays the data of the Model?

We should always create ViewModel. Each View should have its own ViewModel, even if the attributes of the ViewModel are identical with those of the Model.

Assume that a View does not contain the presentation logic and uses Model data instead of ViewModel.

The problem is that if we need to add new data to the UI or display logic in the future, we need to re-plan a UI.

Therefore, it is best to create a ViewModel at the beginning to prevent the increase in demand. In this case, the initial phase of ViewModel is almost the same as that of Model.

4. Use Collection in Lab 7-View

In this Lab section, we will display the Employees list in the View.

Step 1: Change the EmployeeViewModel class

Remove the UserName attribute from the EmployeeViewModel class.

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

Step 2: Create a set

Create a class in the ViewModel folder named EmployeeListViewModel.

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

Step 3: Change the strong View type

Replace the strong type of MyView. cshtml with EmployeeListViewModel.

@using WebApplication1.ViewModels@model EmployeeListViewModel

Step 4: display all employee information in the View.

<body>    Hello @Model.UserName    

Step 5: create a Business Layer for the 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, name it BusinessLayer, and create a new class named EmployeeBusinessLayer. This class 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;    }}

Step 6: transfer data from the 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 to run the application.

Q & A of Lab 7

Can we set the mandatory view type to List?

The answer is yes. We can.

Why do we need to create a separate class, namely, EmployeeListViewModel? Why do we not use a View with a strong type of List <EmployeeListViewModel>?

If we use the List directly instead of the EmployeeListViewModel class, two problems will occur.

Why should we remove the UserName attribute from the EmployeeViewModel and use it as part of the EmployeeListViewModel?

UserName is the same for all employees. If you keep the attributes of UserName in the EmployeeViewModel, redundant code is added and extra memory space for data transmission is added.

5. Conclusion

We have completed 2nd days of MVC learning. In 3rd days, we will bring the project into the next stage.

Let me enjoy it together!

Original article address: Learn MVC Project in 7 days

7-day fun ASP. net mvc-1st-day

This article is compiled by OneAPM engineers. OneAPM is a leading enterprise in the field of basic software in China. It helps enterprise users and developers easily achieve slow real-time crawling of program code and SQL statements. For more technical articles, visit the official OneAPM blog.

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.