Asp.Net MVC Learning Summary (1) - A Simple Introduction to Asp.Net MVC

Keywords: ASP.NET SQL Database xml

A Brief Introduction to MVC

1.1. MVC Concept

View (View)

Representing user interface, for Web applications, it can be summarized as HTML interface, but it may be XHTML, XML and Applet.

Model

Represents a marshal of a user's operation on its data. It can be divided into view model and domain model. View model is a transfer of data between view and controller, and domain model is a set of business logic, background data model and so on. It's a collection of BLL, DAL, Models in the three layers of our learning.

Controller

Controller can be understood as receiving requests from users, matching models with views, and completing users'requests together.

1.2. ASP.NET MVC Principle

When entering a URL in the browser and entering the Route system, the routing system obtains the value of each segment of the URL and gives it to MVC for processing. MVC knows the Action of the request based on the information of the URL, and then processes the model in a series of ways, and then presents the view.

MVC has some limitations on the controller and View, but it has no limitations on the model.

Controllers must implement IController interfaces or inherit Controller classes. The public method in the controller class is called Action Method.

1.3. MVC Project Structure and Meaning

1.4. MVC naming habits

There are two habits in MVC projects

a. Suggest how to organize some files in the project, such as js files placed under the Scripts folder. If you do not follow this habit, these folders and file deletion will not affect the MVC framework itself.

b. Another term is Convention over configuration, which means that if you follow this habit, you don't need additional configuration or coding (especially controllers and views). This habit should be followed as far as possible. If it is violated, many things need to be done in MVC.

There are three main aspects:

Controller naming habit: Controller class must end with Controller, but it can be omitted when referring to this controller. If you want to change this behavior, you need to implement the IControllerFactory interface by yourself. DefaultController Factory is the default to perform the search of the controller.

b. View naming habits: Views or partial views should be placed under the / Views/Controllername folder. For example, if a controller is Demo, then all views of the controller should be placed under / Views/Demo / by default, each Action Method should correspond to one view.

Quantity lets the view name be the same as the Action name, so that you can directly return View() in the Action, and all the controllers of the view placed under the Shared folder can use it.

c. Layout naming habits: Layout files begin with underscores and are placed under shared folders. By default, each view in MVC 3 will use the _layout.cshtml layout, which can be seen in _viewstart.cshtml

1.5. Advantages and disadvantages of ASP.NET MVC

Advantage:

A. Ability to have multiple views corresponding to one model.

B. Because an application is separated into three layers, sometimes changing one of them can satisfy the change of application. The change of an application's business process or business rules only needs to change the model layer of MVC.

C. It is also conducive to software engineering management. Because different layers perform their duties, different applications in each layer have some same characteristics, which is conducive to the generation of management program code through engineering and instrumentalization.

Disadvantages:

A. It increases the complexity of system structure and implementation.

B. Too close connection between view and controller.

C. The inefficient access of view to model data.

1.6. Create the first MVC application

Before creating the first MVC application, let me first explain my computer usage configuration environment: VS2013 and SQLSever2012.

1. Open VS2013 and create a new MVC4 project.

2. Click OK and the following interface will pop up.

3. The default project structure will be generated automatically after clicking on the confirmation.

4. Add a controller by right-clicking on the Controller folder.

5. After clicking the Add button, the HomeController class is generated. By default, the Index() method is generated as follows:

6. Now that the Controller Controller has been created, let's create a View View. There are two ways to add views: one is to add views by right-clicking in the Index() method in the controller, the other is to add a folder with the same name as the HomeController Controller Controller on the View folder, such as: Home folder, and right-click on the folder to add a folder with the same name as the Home Controller. Views with the same name of the Index() method. Choose option 1 to create the method as follows:

7. Finally, after adding the view, the user interface starts to run the browse to view the results.

So here's our first MVC program, Hello World. Does it feel simple? Then let's learn to write a simple test case about the addition, deletion and modification of Asp.Net MVC. Students who have studied Asp.Net can first think about how to use MVC to implement a function of adding, deleting, modifying and checking. Students who haven't studied can think about the connection between the logical three layers and the Model in MVC. The following simple test case will help you understand the concept of MVC more clearly.

1.7. Implement a simple test case about adding, deleting and checking Asp.Net MVC

The results of adding, deleting and modifying test cases are as follows:

1. Prepare database data first.

use master
go
create database Demo
go
use Demo
go
create table Product
(
    ID int primary key identity(1,1),
    Name nvarchar(20),
    Price decimal
)
go
insert into Product values('Computer pad',22),('mouse',55),('keyboard',22),('Reticle',32),('U disc',100),('Coffee',55),('book',99),('milk',5)
go

2. Open VS2013 and create a MVC4 project named MvcFristDemo. The creation steps are the same as above. The steps are not described in detail here. The final project creation is as follows.

The steps to add views are different from the Hello World example above: Because the Model model is used, you need to select the Create Strong Type View model in the following figure to select the Product model when adding views.

Step 1: The code of the Product Controller controller is as follows.

 1 using MvcFirstDemo.Models;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.Mvc;
 7 
 8 namespace MvcFirstDemo.Controllers
 9 {
10     public class ProductController : Controller
11     {
12         public ActionResult List()
13         {
14             List<Product> result = new ProductBll().Select();
15             return View(result);
16         }
17 
18 
19         public ActionResult Add()
20         {
21             return View();
22         }
23         [HttpPost]
24         public ActionResult Add(Product p)
25         {
26             bool result = new ProductBll().Insert(p);
27             return RedirectToAction("List");
28         }
29 
30         public ViewResult Update(int id)
31         {
32             Product p = new ProductBll().GetProductById(id);
33             return View(p);
34         }
35         [HttpPost]
36         public ActionResult Update(Product p)
37         {
38             bool result = new ProductBll().Update(p);
39             return RedirectToAction("List");
40         }
41 
42         public ActionResult Delete(int id)
43         {
44             bool result = new ProductBll().Delete(id);
45             return RedirectToAction("List");
46         }
47     }
48 }

Step 2: The three class codes in the Model folder are as follows.

The code for Product.cs is as follows:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace MvcFirstDemo.Models
 7 {
 8     public class Product
 9     {
10         public int ID { get; set; }
11         public string  Name { get; set; }
12         public decimal Price { get; set; }
13     }
14 }

The code of ProductBll.cs is as follows:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace MvcFirstDemo.Models
 7 {
 8     public class ProductBll
 9     {
10         ProductDal dal = new ProductDal();
11         public List<Product> Select()
12         {
13             return dal.Select();
14         }
15         public Product GetProductById(int id)
16         {
17             return dal.GetProductById(id);
18         }
19         public bool Update(Product p)
20         {
21             return dal.Update(p);
22         }
23 
24         public bool Insert(Product p)
25         {
26             return dal.Insert(p);
27         }
28 
29         public bool Delete(int id)
30         {
31             return dal.Delete(id);
32         }
35     }
36 }

The code of ProductDal.cs is as follows:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Data.SqlClient;
  4 using System.Linq;
  5 using System.Web;
  6 
  7 namespace MvcFirstDemo.Models
  8 {
  9     public class ProductDal
 10     {
 11         string connStr = @"server=PC-201511211346\MSSQLSERVER2;database=Demo;uid=sa;pwd=123456;";
 12         public List<Product> Select()
 13         {
 14             using (SqlConnection conn = new SqlConnection(connStr))
 15             {
 16                 conn.Open();
 17                 string SQL = "select * from Product";
 18                 SqlCommand cmd = new SqlCommand(SQL, conn);
 19                 using (SqlDataReader sdr = cmd.ExecuteReader())
 20                 {
 21                     List<Product> list = new List<Product>();
 22                     Product obj = null;
 23                     while (sdr.Read())
 24                     {
 25                         obj = new Product
 26                         {
 27                             ID = Convert.ToInt32(sdr["ID"]),
 28                             Name = sdr["Name"].ToString(),
 29                             Price = Convert.ToDecimal(sdr["Price"])
 30                         };
 31                         list.Add(obj);
 32                     }
 33                     return list;
 34                 }
 35             }
 36         }
 37 
 38         public bool Insert(Product p)
 39         {
 40             using (SqlConnection conn = new SqlConnection(connStr))
 41             {
 42                 conn.Open();
 43                 string SQL = "insert into Product values(@Name,@Price)";
 44                 SqlCommand cmd = new SqlCommand(SQL, conn);
 45                 cmd.Parameters.AddWithValue("Name", p.Name);
 46                 cmd.Parameters.AddWithValue("Price", p.Price);
 47                 return cmd.ExecuteNonQuery() > 0 ? true : false;
 48             }
 49         }
 50 
 51         public bool Update(Product p)
 52         {
 53             using (SqlConnection conn = new SqlConnection(connStr))
 54             {
 55                 conn.Open();
 56                 string SQL = "update Product set Name=@Name,Price=@Price where ID=@ID";
 57                 SqlCommand cmd = new SqlCommand(SQL, conn);
 58                 cmd.Parameters.AddWithValue("@ID", p.ID);
 59                 cmd.Parameters.AddWithValue("@Name", p.Name);
 60                 cmd.Parameters.AddWithValue("@Price", p.Price);
 61 
 62                 return cmd.ExecuteNonQuery() > 0 ? true : false;
 63             }
 64         }
 65 
 66         public bool Delete(int id)
 67         {
 68             using (SqlConnection conn = new SqlConnection(connStr))
 69             {
 70                 conn.Open();
 71                 string SQL = "delete from Product where ID=@ID";
 72                 SqlCommand cmd = new SqlCommand(SQL, conn);
 73                 cmd.Parameters.AddWithValue("@ID", id);
 74                 return cmd.ExecuteNonQuery() > 0 ? true : false;
 75             }
 76         }
 77 
 78         internal Product GetProductById(int id)
 79         {
 80             using (SqlConnection conn = new SqlConnection(connStr))
 81             {
 82                 conn.Open();
 83                 string SQL = "select * from Product where ID=@ID";
 84                 SqlCommand cmd = new SqlCommand(SQL, conn);
 85                 cmd.Parameters.AddWithValue("@ID", id);
 86                 using (SqlDataReader sdr = cmd.ExecuteReader())
 87                 {
 88                     Product obj = null;
 89                     while (sdr.Read())
 90                     {
 91                         obj = new Product
 92                         {
 93                             ID = Convert.ToInt32(sdr["ID"]),
 94                            Name = sdr["Name"].ToString(),
 95                             Price = Convert.ToDecimal(sdr["Price"])
 96                         };
 97                     }
 98                     return obj;
 99                 }
100             }
101         }
102     }
103 }

Step 3: The three view codes in the View folder are as follows.

What I need to explain here is to change the default generated code in Figure 1 of List.aspx page to the code in Figure 2 and change it to red part code: <%@ Page Language= "C" Inherits= "System.Web.Mvc.ViewPage<List<MvcFirstDemo.Models.Product>">

Why do you want to change it like this? Because the Select() method in the ProductDal.cs class returns a list < Product > collection, and in the List.aspx page, foreach needs to traverse a List < Product > collection-bound display list. If you don't make any changes, the program will run with the error shown in the following figure.

List.aspx page code is as follows:

 1 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<List<MvcFirstDemo.Models.Product>>" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html>
 6 <head runat="server">
 7     <meta name="viewport" content="width=device-width" />
 8     <title>List</title>
 9 </head>
10 <body>
11     <div>
12         <table cellspacing="1"  border="1">
13             <tr>
14                 <td>product ID</td>
15                 <td>Product name</td>
16                 <td>product price</td>
17                 <td>operation <a href="Product/Add">increase</a></td>
18             </tr>
19             <%
20                 foreach (var item in Model)
21                 {  
22             %>
23             <tr>
24                 <td><%=item.ID %></td>
25                 <td><%=item.Name %></td>
26                 <td><%=item.Price %></td>
27                 <td>
28                     <a href="/Product/Update?id=<%=item.ID %>">modify</a>
29                     <a href="/Product/Delete?id=<%=item.ID %>">delete</a>
30                 </td>
31             </tr>
32             <%
33                 } 
34             %>
35         </table>
36     </div>
37 </body>
38 </html>

Add.aspx page code is as follows:

 1 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcFirstDemo.Models.Product>" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html>
 6 <head runat="server">
 7     <meta name="viewport" content="width=device-width" />
 8     <title>Add</title>
 9 </head>
10 <body>
11     <div>
12         <form action="/Product/Add" method="post">
13             <input type="text" name="Name" value=" " />
14             <input type="text" name="Price" value=" " />
15             <input type="submit" name="submit" value="increase" />
16         </form>
17     </div>
18 </body>
19 </html>

The Update.aspx page code is as follows:

 1 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcFirstDemo.Models.Product>" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html>
 6 <head runat="server">
 7     <meta name="viewport" content="width=device-width" />
 8     <title>Update</title>
 9 </head>
10 <body>
11     <div>
12         <form action="/Product/Update" method="post">
13             <input type="hidden" name="ID" value="<%=Model.ID%>" />
14             <input type="text" name="Name" value="<%=Model.Name %>" />
15             <input type="text" name="Price" value="<%=Model.Price %>" />
16             <input type="submit" name="submit" value="modify" />
17         </form>
18     </div>
19 </body>
20 </html>

 

2. Summary of several common mistakes of beginners.

2.1. Error 1

Solution: Changing the parameter name dd in Figure 2 to the same name as the parameter name id passed in Figure 1 can solve the null problem and obtain data.

2.2. Error 2

Solution: In the following figure, where the method overloads the code, one of the methods adds a feature such as [HttpPost], [HttpPut], [HttpPatch], which can solve the problem, and which feature to add depends on the way you initiate the request.

2.3. Error 3

Solution: The solution to this problem has been explained in Step 3 above, and there is no repetition here.

2.4. Error 4

Solution: Change the parameter name in the following figure to the field name in the Product model class to get the data passed by the form.

2.4. Error 5

Solution: Look at the page code and find that there is no error in the page path requested by the browser, but the operation does report an error. The page that requests the URL to specify the path can not be found. What should we do? Let's calmly analyse that there is a knowledge point involved here, that is, your understanding of the principle of MVC. The principle of MVC has been mentioned in the preceding 1.2 and Asp.Net MVC principle sections, so we only need to make the following modifications to solve this problem.

 

 

3. Example Download

Download address: http://pan.baidu.com/s/1hrRO8wG

Summary: In this article, we mainly introduce the related concepts of ASP.NET MVC, and help beginners to deepen their understanding of MVC mode through a simple test case of adding or deleting MVC. Finally, we summarize some common errors of beginners, so that beginners can take less detours.

Posted by chriskiely on Wed, 26 Dec 2018 15:03:07 -0800