Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Experience sharing of MVC Application Development based on .netcore

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Start with a start

Many post-1995 programmers don't understand MVC and need more practice.

MVC is actually not a design pattern, but an architecture pattern / architecture pattern. Architecture is an old name, and now it's basically called architecture.

The model-view-controller (MVC) architecture pattern divides the application into three main components: model (M), view (V) and controller (C). MVC mode helps to create applications that are easier to test and update than traditional monolithic applications.

Model (M): a class that represents application data. The model class uses validation logic to enforce business rules on this data. Typically, model objects retrieve the model state and store it in the database.

View (V): a view is a component that displays the application user interface (UI). This UI usually displays model data.

Controller (C): the class that handles browser requests. They retrieve the model data and call the view template that returns the response. In MVC applications, the view displays only information; the controller processes and responds to user input and interaction. For example, the controller processes routing data and query string values and passes them to the model. The model can use these values to query the database.

1.1 MVC benefits

The MVC pattern helps create applications that separate different application features (input logic, business logic, and UI logic) while loosely coupling these elements.

This pattern specifies the location of each type of logic in the application. The UI logic is in the view. The input logic is located in the controller. The business logic is in the model.

This isolation helps control the complexity of building an application because it can be used to process code that implements one feature at a time without affecting other features. For example, you don't have to rely on business logic code when dealing with view code

1.2Create a MVC project

1.3 add a controller

1.4 add HTTP Endpoint calls

Each public method in the controller can be called as an HTTP endpoint.

An HTTP endpoint is an orientable URL (for example, https://localhost:44399/EdisonTest) in a Web application that combines the network location localhost:44399 of the Web server, such as the protocol HTTPS, TCP port, and the target URI EdisonTest.

2 further

2.1 routin

MVC invokes the controller class (and its operation methods) based on the inbound URL. The default URL routing logic used by MVC uses the following format to determine the calling code:

/ [Controller] / [ActionName] / [Parameters]

Set the route format in the Configure method of the Startup.cs file.

If you browse to the application and no URL segment is provided, it defaults to the "Home" controller and "Index" method specified in the left red line.

The first URL section determines the controller class to run. Localhost: 44399 maps to the EdisonTestController class.

The second URL section determines the method of operation on the class. Localhost:44399/EdisonTest/GetOwnerName will trigger the GetOwnerName run of the EdisonTestController class. Notice that you only need to browse to localhost:xxxx/EdisonTest, and the GetOwnerName method is called by default. The reason is that GetOwnerName is the default method, and if the method name is not explicitly specified, it will be called on the controller.

The third URL segment (id) is for routing data.

Test:

2.2 add parameters

Modify the code to pass some parameter information from the URL to the controller.

L is indicated by the C# optional parameters feature, which defaults to 1 when no value is passed for the numTimes parameter.

Use HtmlEncoder.Default.Encode to prevent malicious input (that is, JavaScript) from harming the application.

L use interpolated strings in $"I am Edison.Feng, you are {name}. Number of Times: {numTimes}".

Test:

2.3 Parameter routing

Parameters can also be used as routes:

Test:

Question1: how is the third part of the route resolved?

Question 2: what does the question mark in the third part of the route indicate?

2.4 add a View view

Purpose: to eliminate the previous hard coding and not directly return the contents of the HTML file, but to return the view object:

Use the Razor view file to encapsulate and generate the HTML response for the client.

Use Razor to create a view template file. Razor-based templates have a ".cshtml" file extension. They provide an ingenious way to create HTML output using C #.

Right-click the Views folder, then click add > New folder, and name the folder EdisonTest.

Right-click the Views/EdisonTest folder, and then click add > New item.

L in the add New item-MvcMovie dialog box

L in the search box in the upper right corner, enter "View"

L Select Razor View

L keep the value of the name box: getownername.cshtml.

L Select add

Modify the view file getownername.cshtml:

Modify the default route, Startup.cs:

Modify the controller to add a get method:

Test:

2.5 pass point data to the view

Use ViewData to pass data between the view and the controller:

(1) modify the controller

(2) modify the view

(3) testing

3 database operation

3.1 store the real data in the database and take it out

Use these classes in conjunction with Entity Framework Core (EF Core) to process the database. EF Core is an object-relational mapping (ORM) framework that simplifies the data access code that needs to be written.

The model classes to be created are called POCO classes (derived from "simple legacy CLR objects") because they do not have any dependencies on EF Core. They define only the properties of the data that will be stored in the database.

3.2 add a model Model

Select the Models folder and right-click the menu.

3.3 add attributes

The database requires an Id field to get the primary key.

[DataType (DataType.Date)]: the DataType attribute specifies the type of data (Date).

With this feature:

Users do not need to enter time information in the data field.

Only the date is displayed, not the time information.

DataAnnotations

3.4 scaffolding tools

L scaffolding: Scaffold, or translated as base frame

.net core generates pages through the scaffolding tool (Scaffolded Item) to perform create, read, update, and delete (CRUD) operations on the model Model

3.5 views using EF Core

L model class: select the model class Movie you just built

L data Context class: new, named MvcMovie1Context by default

L view: default

L controller name: default

3.6 which files are automatically created by the "building base" process?

L EF Core database Context class

L controller

L Razor view file (CRUD)

L Create

L Index

L Details

L Edit

L Delete

3.7 EF Core Migration Featur

Do not use EFCore migration function, only "build the base frame", then the program runs prompt SqlException: cannot open the database

L initial migration

L enter PMC (that is, the package management console)

Type Add-Migration Initial and enter to generate the code to create the initial database schema based on the model specified in the MvcMovieContext class. The Initial parameter is the migration name

Type Update-Database and enter, and run the Up method in the Migrations/ {time-stamp} _ InitialCreate.cs file. Migrations/ {time-stamp} _ InitialCreate.cs is used to create the database

L dependency injection

The scaffolding tool has injected the data context class MvcMovie1Context into container services

L AddDbContext specifies the database and connection string

L = > is the Lambda operator

The data context class coordinates the EF Core function for the Movie model

L (create, read, update, delete, etc.)

L data table of the database corresponding to the entity set DbSet

L passes the connection string name to the context by calling a method in the DbContextOptions object.

When developing locally, the ASP.NET Core configuration system reads the database connection string in the appsettings.json file.

3.8 CRUD: Details

L Details method

Pass strongly typed model objects to the view: this strongly typed method enables better compile-time checking of code

L FirstOrDefaultAsync returns the first element that meets the condition, or the default element if the condition is not met

L m = > m.Id = = the ID of the id element is equal to the given ID

L Details.cshtml

L @ model MvcMovie1.Models.Movie

L by including the @ model statement at the top of the view file

L can specify the type of object expected by the view

3.9 CRUD: Index

L Index method

L ToListAsync creates a List asynchronously

L Index.cshtml

3.10 CRUD: Edit

3.11 CRUD: Create

3.12 CRUD: Delete

4 expand more

4.1 Database connection string

L DbContextOptionsBuilder.UseSqlServer

L IConfiguration.GetConnectionString

L AppSettings.json

3.2 SQL Server Express LocalDB

L SQL Server object Explorer

L View designer

L View data

4.3 Database seed

L database seed: initialize data when there is no data

L modify Main method

L add SeedData class

Test:

Test after deleting the data in the database, as shown in the figure.

L View data after refreshing the database

4.4 modify the display list

L modify column Title.

L modify column data display format

4.5 search by title

L add a parameter to the Index operation.

L s = > s.Title.Contains () the code is a Lambda expression

L Lambda expressions are used as parameters to standard query operator methods in method-based LINQ queries, such as the Where method or Contains, and are not executed until the LINQ query is defined or modified by calling methods such as Where, Contains, or OrderBy. This means that the evaluation of the expression is delayed until it actually iterates through its implemented value or calls the ToListAsync method.

The Contains method runs on the database, not in the C # code

Bind two input tags in cshtml.

The l tag uses the form tag helper, and the filter string is published to the Index action of the movie controller when the form is submitted.

L add a POST Index operation

L test

L the filter page no longer appears

L modify index.cshtml

L test: you can go to the filter page

4.6 search by genre

L modify index operation method

L System.linq namespace with two static classes: Queryable and Enumerable

L IQueryable:where conditional access expression, delayed execution

L IEnumerable:where condition receives a predicate expression (delegate) and executes it immediately

L SelectList is a collection of SelectListItem, used in conjunction with tags

L modify index.cshtml

The top sentence is changed to: @ model MvcMovie1.Models.GenreViewModel

L in Title:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report