Seven days Learn ASP (ii)--asp.net MVC data Transfer

Source: Internet
Author: User


After the first day of study, we believe you have some basic understanding of MVC.

This section is based on the previous section, so you need to make sure you have the content of the previous section. The goal of this chapter is to create a small MVC project with best practice solutions at the end of today's learning, and the main goal of this section is to understand the data transfer problem between MVC. We will step in-depth and add new features to make the project more and more perfect.


Series Articles

Seven-day Learning ASP (one)--in-depth understanding of ASP.

Value passing between controller and view

A static view has been created in the previous section of experiment two. However, in actual use, view is often used to display dynamic data. In the experiment three, the data will be displayed dynamically in the view.

View will get the data from the model from the controller.

Model is the layer in MVC that represents business data.

Experiment 3--using View data

ViewData is equivalent to a data dictionary that contains all the data passed between Controlle and view. The controller adds new data items to the dictionary, and the view reads the data from the dictionary.

1. Creating the Model class

Create a new employee class under the Model folder, as follows.

1:public class Employee
2:
3: {
4:public string FirstName {get; set;}
5:
6:public string LastName {get; set;}
7:
8:public int Salary {get; set;}
9:
10:}

2. Get the model from the controller

Create an Employee object in the GetView method:

1:employee emp = new Employee ();
2:emp. FirstName = "Sukesh";
3:emp. Lastname= "Marla";
4:emp. Salary = 20000;

Note: Be sure to use the using statement to include this class, or use the full name of the class.

1:using Webapplication1.models;

3. Create ViewData and return to view

Stores the employee object in ViewData.

1:viewdata["Employee"] = EMP;
2:return View ("MyView");

4. Show employee data in view

Open myview.cshtml.

Obtain the employee data from ViewData and display it as follows:

1: <div>
2: @{
3:webapplication1.models.employee emp= (WebApplication1.Models.Employee)
4:viewdata["Employee"];
5:}
6:
7: <b>employee Details </b><br/>
8:employee Name: @[email protected] <br/>
9:employee Salary: @emp. Salary.tostring ("C")
Ten: </div>

5. Test output

Press F5 to run


About Experiment 3

1. What is the difference between writing razor code with curly braces and no curly braces?

In the experiment three @emp. FirstName can use the following script instead

1: @{
2:response.write (EMP. FirstName);
3:}

The @ symbol does not have curly braces but simply displays the value of a variable or an expression

2. Why a cast type is required

ViewData can manipulate internal objects, and each time a new value is added, it is encapsulated into an object type, so it needs to be decompressed each time to extract the value.

3. @emp. FirstName @emp. What special meaning does LastName have?

means that LastName appears after FirstName and automatically adds spaces.

4. Why is the hard-coded in employee created by the controller?

In this article it is only for experimental purposes, so hard-coded, in practice, is obtained from the database or Web services.

5. Database logic, data access layer, what is the business layer?

The data access layer is implicitly present in ASP. MVC definition does not contain the definition of the data access layer.

The business layer is the forerunner of the interpreter and is part of the model.

A complete MVC structure


The use of experimental 4--viewbag

1. Create a View Bag

On the basis of experiment three, use the following script instead of the code in the third step.

1:viewbag.employee = EMP;

2. Show EmployeeData in view

Use the following code to replace the code in the fourth step of experiment three:

1: @{
2:webapplication1.models.employee emp = (WebApplication1.Models.Employee)
3:viewbag.employee;
4:}
5:employee Details
6:
7:employee Name: @emp. FirstName @emp. LastName
8:
9:employee Salary: @emp. Salary.tostring ("C")

3. Test output

Operation Result:


About Experiment 4

Can I pass ViewData and get viewbag when I receive it?

The answer is yes, and vice versa. As I said before, ViewBag is just a viewdata of sugar.

The problem of ViewData and ViewBag

ViewData and ViewBag are the contents of the value passed between the Contoller and the view. But in the actual use of the process, they are not the best choice, next we look at the disadvantages of using them:

performance issues; The values in ViewData are object types that must be cast to the appropriate type before they are used. Additional performance burdens will be added.

There is no compile-time error without type safety, and if you attempt to convert it to the wrong type, the runtime will give an error. Good programming experience tells us that errors must be captured at compile time.

There is no proper connection between data transmission and data reception; in MVC, controllers and view are loosely connected. The controller is unable to capture the view changes and the view cannot capture the changes that have occurred inside the controller. A viewdata or ViewBag value is passed from the controller, and when the developer is writing to the view, it must record what value is about to be obtained from the controller. If the controller is not the same developer as the view developer, the development effort becomes very difficult. Can cause many run-time problems and reduce development efficiency.

Experiment 5--Understanding strongly typed view

The source of all the problems caused by ViewData and ViewBag is the data type. The data type of the parameter value is encapsulated in the ViewData, called the object.

If you can set the data type that the parameter passes between the controller and the view, the above problem is resolved, so the strongly typed view is derived.

Next, let's look at a simple example, if the salary is greater than 15000, show * * *, below the display green.

1. Create a strong type of view

Add the following code at the top of the view:

@model WebApplication1.Models.Employee

2. Display data

Enter @model inside the view. You will see the properties of the Model class


Add the following code to display the data:

1:employee Details
2:
3:employee Name: @Model. FirstName @Model. LastName
4:
5: @if (model.salary>15000)
6: {
7: <span style= "Background-color:yellow" >
8:employee Salary: @Model. salary.tostring ("C")
9: </span>
10:}
11:else
12: {
: <span style= "Background-color:green" >
14:
15:employee Salary: @Model. salary.tostring ("C")
: </span>
17:}

3. Pass the model data from the controller action method.

Modify the Action code

1:employee emp = new Employee ();
2:emp. FirstName = "Sukesh";
3:emp. Lastname= "Marla";
4:emp. Salary = 20000;
5:return View ("MyView", EMP);

4. Test output


About Experiment 5

Do you need to declare the full name of the class when you use the class in view (Namespace.ClassName)?

Adding the following statement does not require you to add a full name.

1: @using webapplication1.models
2: @model Employee

Do I have to set the strongly typed View5 of view or not use ViewData and viewbag?

Setting a strongly typed view is the best solution.

Can I set the view to a strong type used by multiple model?

No, the actual project ends with a point when you want to display more than one model in a view. The workaround for this issue is discussed in the next section.

Understanding view Model in ASP.

The basic principles of MVC have been violated in experiment 5. According to Mvc,v is a view-only UI and does not contain any logical layers. The following three points in our experiment 5 violate MVC's architecture rules.

1. Additional last name and first name display full name--Logical layer

2. Using currency to display wages--Logic layer

3. Use different colors to represent payroll values, and use simple logic to change the appearance of HTML elements. --Logic Layer

ViewModel Workaround

ViewModel is an implicitly-declared layer in an ASP. NET MVC application. It is used to maintain data transfer between model and view, which is the data container of view.

The difference between Model and ViewModel

Model is a business-related data that is created from the business and data structures. ViewModel is a view-related data. is created from view.

How the work Works

The Controller handles user interaction logic or simple judgments. Handling user Needs

Controller gets one or more model data

Controller to decide which view best matches the user's request

The Controller will create and initialize the ViewModel object based on the model data and view requirements.

The Controller passes ViewModel data to the view in objects such as ViewData or viewbag or strongly typed view.

Controller returns to view.

How is the relationship between View and ViewModel?

View will become a strongly-typed view of ViewModel.

How are model and ViewModel related?

The model and ViewModel are independent of each other, and the controller creates and initializes the ViewModel object based on the model object.

Now let's look at experiment 6:

Experiment 6--realize ViewModel

1. Create a new Folder

Create a new folder in your project and name it viewmodels.

2. New Employeeviewmodel

To achieve the experimental goal, we first list our experimental requirements:

1. First and last names should be displayed in combination.

2. Use Currency display quantity

3. Salary is displayed in different colors

4. The currently logged in user also needs to be displayed in the view.

In the ViewModels class, create a new class and name Employeeviewmodel as follows:

1:public class Employeeviewmodel
2: {
3:public string EmployeeName {get; set;}
4:public string Salary {get; set;}
5:public string Salarycolor {get; set;}
6:public string Username{get;set;}
7:}
Note that the first and last names should use the EmployeeName attribute. The data type of the salary property is a string, and two new attributes are added called Salarycolor and username.
3. Use ViewModel in view

Experimental V has created a strongly typed employee for view. Change it to Employeeviewmodel

1: @using webapplication1.viewmodels
2: @model Employeeviewmodel

4. Displaying Data in view

Use the following script instead of the contents of the View section

1:hello @Model. UserName
2: 3: <div>
4: <b>employee details</b><br/>
5:employee Name: @Model. EmployeeName <br/>
6: <span style= "Background-color: @Model. Salarycolor" >
7:employee Salary: @Model. Salary
8: </span>
9: </div>

5. New and passed ViewModel

In the GetView method, the model data is obtained and cast to the ViewModel object.

1:public ActionResult GetView ()
2: {
3:employee emp = new Employee ();
4:emp. FirstName = "Sukesh";
5:emp. Lastname= "Marla";
6:emp. Salary = 20000;
7:
8:employeeviewmodel vmemp = new Employeeviewmodel ();
9:vmemp.employeename = emp. FirstName + "" + emp. LastName;
10:vmemp.salary = emp. Salary.tostring ("C");
11:if (EMP. salary>15000)
12: {
13:vmemp.salarycolor= "Yellow";
14:}
15:else
16: {
17:vmemp.salarycolor = "green";
18:}
19:
20:vmemp.username = "Admin"
21st:
22:return View ("MyView", vmemp);
23:}

6. Test output


Although the results are similar, the view does not contain any business logic.

About Experiment 6

Does it mean that each model has a ViewModel?

Each view has its corresponding viewmodel.

is an association between model and ViewModel a good way to implement it?

The best is that the model and the ViewModel are independent of each other.

Do I need to create viewmodel every time? Do I need to create a viewmodel if view does not contain any rendering logic to display only model data?

The recommendation is to create viewmodel each time, each view should have a corresponding ViewModel, although ViewModel contains the same attributes as the model.

Suppose a view does not contain any rendering logic and only shows model data, what happens when we do not create ViewModel?

Unable to meet the needs of the future, if we need to add new data in the future, we need to create a new UI from scratch, so if we keep the rules and create ViewModel from the beginning, this will not happen. In this example, the initial phase of the ViewModel will be almost identical to the model.

Experiment 7--A view with a set

In this experiment, the employee list is displayed in view.

1. Modify the Employeeviewmodel class

Delete Username Property

1:public class Employeeviewmodel
2: {
3:public string EmployeeName {get; set;}
4:public string Salary {get; set;}
5:public string Salarycolor {get; set;}
6:}

2. Create a combined ViewModel

Under the ViewModels file, create a new class and name it Employeelistviewmodel

1:public class Employeelistviewmodel
2: {
3:public list<employeeviewmodel> Employees {get; set;}
4:public string UserName {get; set;}
5:}

3. Modifying the type of a strongly-typed view

1: @using webapplication1.viewmodels
2: @model Employeelistviewmodel

4. Show all employee in view

1: <body>
2:hello @Model. UserName
3: 4: <div>
5: <table>
6: <tr>
7: <th>employee name</th>
8: <th>Salary</th>
9: </tr>
Ten: @foreach (Employeeviewmodel item in Model.employees)
11: {
: <tr>
: <td> @item. Employeename</td>
£ º <TD style= "Background-color: @item. Salarycolor "> @item. Salary</td>
: </tr>
16:}
: </table>
: </div>
: </body>

5. Create business logic for employee

Create a new class and name it Employeebusinesslayer with the GetEmployees () method.

1:public class Employeebusinesslayer
2: {
3:public list<employee> GetEmployees ()
4: {
5:list<employee> employees = new list<employee> ();
6:employee emp = new Employee ();
7:emp. FirstName = "Johnson";
8:emp. LastName = "Fernandes";
9:emp. Salary = 14000;
10:employees. ADD (EMP);
11:
12:emp = new Employee ();
13:emp. FirstName = "Michael";
14:emp. LastName = "Jackson";
15:emp. Salary = 16000;
16:employees. ADD (EMP);
17:
18:emp = new Employee ();
19:emp. FirstName = "Robert";
20:emp. LastName = "Pattinson";
21:emp. Salary = 20000;
22:employees. ADD (EMP);
23:
24:return employees;
25:}
26:}
: </employee></employee></employee>

6. Transfer the parameters from the controller

1:public ActionResult GetView ()
2: {
3:employeelistviewmodel Employeelistviewmodel = new Employeelistviewmodel ();
4:
5:employeebusinesslayer Empbal = new Employeebusinesslayer ();
6:list<employee> employees = Empbal.getemployees ();
7:
8:list<employeeviewmodel> empviewmodels = new list<employeeviewmodel> ();
9:
10:foreach (Employee emp in employees)
11: {
12:employeeviewmodel Empviewmodel = new Employeeviewmodel ();
13:empviewmodel.employeename = emp. FirstName + "" + emp. LastName;
14:empviewmodel.salary = emp. Salary.tostring ("C");
15:if (EMP. Salary > 15000)
16: {
17:empviewmodel.salarycolor = "Yellow";
18:}
19:else
20: {
21:empviewmodel.salarycolor = "green";
22:}
23:empviewmodels.add (Empviewmodel);
24:}
25:employeelistviewmodel.employees = Empviewmodels;
26:employeelistviewmodel.username = "Admin";
27:return View ("MyView", Employeelistviewmodel);
28:}
£ º </employeeviewmodel></employeeviewmodel></employee>

7. Implementation


About Experiment 7

Can I make a strongly typed view list?

Why do you want to create a new Employeelistviewmodel separate class without directly using the list of strongly typed view?    1. Plan the presentation logic 2 that will appear in the future. The Username property. Username is a property that is unrelated to employees and is related to the full view. Why delete Employeeviewmodel's Username property instead of as part of Employeelistviewmodel? UserName is the same and does not require adding UserName in Employeeviewmodel.

Conclusion

That's what we're talking about the next day, and on the third day we'll learn something new.

Original link: Http://www.codeproject.com/Articles/897559/Learn-MVC-in-days-Day



This article is from the "Grape City Control Technology Team Blog" blog, be sure to keep this source http://powertoolsteam.blog.51cto.com/2369428/1669092

Seven days Learn ASP (ii)--asp.net MVC data Transfer

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.