MVC pattern
MVC development model
The role of MVC pattern
- The main design goal is to separate the user interface and the logic layer, so that developers can better pay attention to the design and testing of the logic layer, and make the entire program have a clear architecture
The composition of MVC
Modal (model layer) View (view layer) Controller (controller)
- Model : A model object is an application component that implements the logic of the application data domain, usually called a "data model". The model object retrieves the model state and stores it in the database
- View : A view is a component that displays the user interface (UI) of an application. Usually, this UI is created by model data
- Controller : The controller is the component that handles user interaction, uses the model, and selects the view to display the interface. In an MVC application, the view only displays the interface; the controller is used to process and respond to user input and interaction
Directory structure of MVC program
table of Contents | Description |
---|---|
App_Start | Contains multiple static configuration classes to perform application initialization tasks |
Content | Place the static content of the application |
Controller | Place the controller file, the controller file is a file with the extension .cs |
Models | File where data model objects are placed |
Views | Place the view file, the file extension is .cshtml or aspx |
Script | Place JavaScript and jQuery files |
MVC routing and data delivery
Routing overview:
A well-designed URL should meet the following requirements: the
domain name is easy to remember and spell;
short and entered; it
can reflect the structure of the site; it is
durable and cannot be changed.
- There is already a default routing rule definition in the MVC application, the code is in the ./App_Start/ RouteConfig.cs file
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default", // 路由名称 名称必须唯一
url: "{controller}/{action}/{id}", // URL模式
defaults: new {
controller = "Home", action = "Index", id = UrlParameter.Optional }); // 定义每个路由参数的默认值
}
}
- How to configure custom routing rules
routes.MapRoute(
name: "News",
url: "{controller}/{action}/{year}-{month}-{day}",
defaults: new {
controller = "Home", action = "News", id = UrlParameter.Optional });
URL格式:http://localhost/Home/News/2012-12-21
The controller passes data to the view
The controller passes a small amount of data to the view, the three common ones are:
- ViewData : dictionary type, which stores key/value pair data. ViewData is only valid in one HTTP request, and its value will be cleared automatically when the request is over.
- ViewBag : Equivalent to ViewData, but the internal implementation is completely different. ViewBag stores not key-value pair data, but dynamic dynamic type data.
- TempData : Saved in the Session by default, the controller requests TempData from the Session each time, and then clears the Session. Based on this fact, after each request ends, the life cycle of TempData ends at the same time.
Controller commonly used return method
Method name | Description |
---|---|
ViewResult | Display 8 overloads of a specific View page |
RedirectToRoutResult | RedirectToAction The result of the return method is to jump to other actions in this project |
RedirectResult | RedirectAction The purpose of the returned results is to jump to the page without any restrictions |
FileResult | File The result of the return method is to output a specific file to the client |
ContentResult | The purpose of the return Content method is to output a string |
JsonResult | The return Json method outputs the object as an Json object |
JavaScriptResult | The return JavaScript method dynamically outputs a section js |
HttpStatusCodeResult | Return HttpStatusCodeRestult method dynamic output status code (200, 400, 500, etc.) |
List through the EF framework
ORM overview:
- SNAKE
- ORM stands for "object-relational mapping"
- ORM is the process of expressing the data in the relational database in the form of objects, and organizing these objects in an object-oriented way to realize the business logic of the system
- The specific meaning of ORM
- O corresponds to the class in the program
- R is the relation, corresponding to the relational table in the database
- M represents the mapping relationship between objects in the program and relational tables in the database
- Entity Framework (EF for short)
- Recommended ORM framework for ASP.NET MVC applications
- Support multiple databases
- Mapping engine supports stored procedures
- Provide Visual Studio integrated tools to perform visual operations
DB First mode
- Database First
- Called "database first", that is, create a database first, and then generate a data model
- The premise of this mode is that the database already exists and works normally. Then use the Visual Studio EF model designer to generate a data model based on the database
- In ASP.NET MVC applications, all data model-related classes are placed in the /Models directory by default
- 1. Start the EF wizard
- After creating the ASP.NET MVC application, open the "Add New Item" dialog box, select "Data", and select "ADO.NET Entity Data Model" to open the EF wizard
- 2. Database generation
- Click the "Add" button, in the "Entity Data Model Wizard" dialog box, select "Generate from database (EF Designer from database)"
- 3. Database connection
- Click "Next", in the "Entity Data Model Wizard" dialog box, create a database connection, connect to the "DBName" database, the EF wizard automatically generates the connection string
- 4. Data sheet (check the required data sheet)
- 5. Click Finish
Database context object DBContext
- The DBTESTEntities class automatically generated by the EF wizard, called "database context operation class", is located in
/Models/Model1.Context.cs
- The generated Dept, Employee class is called "business entity class"
The .edmx file is an XML file that is used to define the conceptual model, the storage model and the mapping between these models. The
SSDL storage model, the entities in the database (the form of fixing the relationship of each entity to the table)
CSDL conceptual model, procedural language model defined by an angle, in which the entity definition, primary keys, attributes, etc. are associated corresponding to the .NET Framework type
mappings to connect the conceptual model and the storage model, to perform the operations, i.e., an entity attribute (concepts Model) corresponding entity. Field (storage model)
Razor syntax
- Razor
- Not a code language, but the code engine used in the view
- It presents web server-side code functions with a concise client-like grammatical structure
- It replaces the "<%…%>" code block syntax of ASPX pages
- Use "@" at the beginning of writing, "@" is the Razor logo
- @ … @ Razor Annotation
Razor syntax data processing is on the server side
Razor syntax has three formats:
@表达式
generally
@(表达式)
mixed long format
@{ C#代码块(混HTML) }
is used to process the formatted display of collection data blocks
Strong type
- Means that the variable has clearly specified its type when it is defined. Compared with "strong type" is "weak type" (object type belongs to "weak type")
Model
- By default, the Model property in the view can be directly accessed by the viewing code, and is a dynamic type. However, in order to improve the efficiency and accuracy of the development view, you can explicitly specify the specific type of the Model, and use the "strongly typed" data ( strong type can. Out the attribute name )
strong type declaration:@model 模型对象(集合)
Add through the EF framework
HTML helper output form
- Output hyperlink writing:
@Html.ActionLink("LinkText","ActionLinkName")
@Html.ActionLink("LinkText","ActionLinkName","ControllerName")
@Html.ActionLink("LinkText","ActionLinkName",new{id=xxx,page=z})
- ASP.NET MVC framework has built-in HTML auxiliary methods related to multiple forms
HTML helper | Description |
---|---|
Html.BeginForm() | Output <form> label |
Html.CheckBox() | Output <input type="checkbox"> label |
Html.DropDownList() | Output <select> label |
Html.Password() | Output <input type="password"> label |
Html.RadioButton() | Output <input type="radio"> label |
Html.TextArea() | Output <textarea> label |
Html.TextBox() | Output <input type="text"> label |
Data addition through the EF framework
The database context class is used to track and identify the changes of business entity objects and is the entry point for database access operations. Without this class, EF will not work. The following code is pseudo code
public partial class DBTESTEntities: DbContext // EF框架可自动生成,一般无需改动
{
public EntityTEntities ()
: base("name=EntityTEntities") // 关联数据库连接串
{
}
//用于在上下文对象初始化后执行相关的配置操作
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
//业务实体类
public DbSet<Entity> Entity {
get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
Entity entity = new Entity() // 实例化实体对象
{
FieldName = Request["FieldName"]
};
// using语句可自动释放 数据库上下文对象 占用的数据库资源
using (DBNameTEntities db = new DBNameTEntities())
{
db.Dept.Add(entity); // 将数据添加进实体上下文
db.SaveChanges(); // 将更改保存数据库
}
return View();
}
}
MVC upload file
public ActionResult UploadFile(HttpPostedFileBase fileName) // 暂不做文件类型判断
{
fileName.SaveAs(Request.MapPath("~/upload/") + fileName);
return Content("OK");
}
- Judging the file type is not based on the file suffix name but the binary code of the name
extension name | Binary code |
---|---|
JPG | 255216 |
GIF | 7173 |
BMP | 6677 |
PNG | 13780 |
RAR | 8297 |
jpg | 255216 |
exe | 7790 |
xml | 6063 |
html | 6033 |
aspx | 239187 |
cs | 117115 |
js | 119105 |
txt | 210187 |
sql | 255254 |