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

Example Analysis of Model, View and Controller in C #

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the example analysis of model, view and controller in C#, which is very detailed and has certain reference value. Friends who are interested must finish it!

Sample ASP.NET MVC application

The default Visual Studio template for creating ASP.NET MVC Web programs includes an extremely simple example program that can be used to understand different parts of the ASP.NET MVC Web program. Let's take advantage of this simple program in this tutorial.

Run Visual Studio 2008, select File, New (see figure 1), and create the ASP.NET MVC program with the MVC template. In the New Project dialog box, select your favorite programming language in Project Type (P) (Visual Basic or C #), and select ASP.NET MVC Web Application under templates. Click the OK button.

Figure 1 New Project dialog box

After creating the new ASP.NET MVC program, the Create Unit Test Project dialog box appears (see figure 2). This dialog box will create a separate project for you to test your ASP.NET MVC program in the solution. Select the options No, do not create a unit test project and click the OK button.

Figure 2 create a unit test dialog box

The ASP.NET MVC program is created. You will see several folders and files in the solution Explorer window. In particular, you will see three folders named Models,Views and Controllers. As the name implies, these three folders contain files that implement the model, view, and controller.

If you expand the Controllers folder, you will see a file named AccountController.cs and a file named HomeControllers.cs. Expand the Views folder and you will see three subfolders named Account,Home and Shared. Expand the Home folder and you will see two files named About.aspx and Index.aspx (see figure 3). These files make up a sample program that includes the default ASP.NET MVC template.

Figure 3 solution Explorer window

Select Debug and start Debug to run the sample program. Or press F5.

The first time you run the ASP.NET program, the dialog box shown in figure 4 appears, and you are advised to start debugging. Click the "OK" button and the program will run.

Figure 4 debugging unstarted dialog box

When you run the ASP.NET MVC program, Visual Studio will run your program in the browser. The sample program consists of two pages: Index page and About page. When the program first starts, the Index page appears (see figure 5). You can navigate to the About page by clicking on the menu link at the top right of the program.

Figure 5 Index page

Notice the URL in the browser's address bar. When you click the About menu link, the URL in the address bar becomes / Home/About.

Close the browser window and go back to Visual Studio. You can't find the file in the path Home/About. This file doesn't exist. How is that possible?

A URL is not equal to a page

When a traditional ASP.NEW Web forms program or ASP program is generated, a URL corresponds to a web page. If you make a request to a page called SomePage.aspx on the server, it is best to have such a page called SomePage.aspx on disk. If the SomePage.aspx file does not exist, you will get an ugly 404-Page Not Found error.

In contrast, when you generate an ASP.NET MVC program, there is no correspondence between the URL of the browser address you enter and the file you are looking for in the program. In

In the ASP.NET MVC program, a URL does not correspond to a page on disk but corresponds to a controller action.

In traditional ASP.NET or ASP programs, browser requests are mapped to pages. In contrast, in the ASP.NET MVC program, the browser request is mapped to the controller action. ASP.NET Web forms programs are content-centric. On the contrary, ASP.NET MVC programs focus on program logic.

Understand ASP.NET Routing

The browser requests a mapping of the controller action through an ASP.NET framework feature called ASP.NET Routing. ASP.NET Routing is used by the ASP.NET MVC framework to route requests to the controller action.

ASP.NET Routing uses a routing table to handle incoming requests. This routing table is created when the web program runs for the first time. It is created in the Global.asax file. The default MVC Global.asax file is shown in code 1.

Code 1-Global.asax

Using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Routing;namespace MvcApplication1 {/ / Note: For instructions on enabling IIS6 or IIS7 classic mode, / / visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication: System.Web.HttpApplication {public static void RegisterRoutes (RouteCollection routes) {routes.IgnoreRoute ("{resource} .axd / {* pathInfo}") Routes.MapRoute ("Default", / / Route name "{controller} / {action} / {id}", / / URL with parameters new {controller = "Home", action = "Index", id = ""} / / Parameter defaults) } protected void Application_Start () {RegisterRoutes (RouteTable.Routes);}

The Application_Start () method is called when the ASP.NET program starts for the first time. In code 1, this method calls the RegisterRoutes () method to create a default routing table.

The default routing table includes only one route. This default route divides the incoming request into three segments (a URL segment is anything between two slashes). The first segment maps to the controller name, the second to the action name, and the last to a parameter named Id passed to action.

For example, consider the following URL:

/ Product/Details/3

The URL is parsed into three parameters like this:

Controller = Product

Action = Details

Id = 3

The default route defined in the Global.asax file includes the default values for all three parameters. The default controller is Home, the default Action is Index, and the default Id is empty string. With these default values in mind, consider how the following URL is parsed:

/ Employee

The URL is parsed into three parameters like this:

Controller = Employee

Action = Index

Id =

Finally, if you open the ASP.NET MVC program without typing any URL (for example, http://localhost), the URL parses like this:

Controller = Home

Action = Index

Id =

The request is routed to the Index () action of the HomeController class.

Understand the controller

The controller is responsible for controlling the way users interact with MVC programs. The controller includes flow control logic of ASP.NET MVC program. The controller decides what response to return when the user sends a browser request. A controller is a class (for example, a Visual Basic or C # class). The sample ASP.NET MVC program includes a controller named HomeController.cs located in the Controllers folder. The contents of the HomeController.cs file are reproduced in code 2.

Code 2-HomeController.cs

Using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MvcApplication1.Controllers {[HandleError] public class HomeController: Controller {public ActionResult Index () {ViewData ["Title"] = "Home Page"; ViewData ["Message"] = "Welcome to ASP.NET MVC!"; return View () } public ActionResult About () {ViewData ["Title"] = "About Page"; return View ();}

Notice that HomeController has two methods named Index () and About (). These two methods correspond to the two action exposed by the controller. URL/ Home/Index calls the HomeController.Index () method and URL/ Home/ About calls the HomeController.About () method.

Any public method in the controller is exposed as the controller action. You have to be very careful about this. This means that people can call any public method in the controller as long as they access the Internet and enter the correct URL in the browser.

Understand the view

Both the Index () and About () action exposed by HomeController return a view. The view includes HTML tags and content sent to the browser. In an ASP.NET MVC program, a view is equivalent to a page. You have to create the view in the right place. HomeController.Index () action returns a view located in the following path:

/ Views/Home/Index.aspx

HomeController.About () action returns a view located in the following path:

/ Views/Home/About.aspx

In general, if you want to return the view for the controller action, you need to create a subfolder under the Views folder with the same name as the controller. Within this subfolder, you have to create an .aspx file with the same name as the controller action.

The file in code 3 contains the About.aspx view.

Code 3-About.aspx

About

Put content here.

If you ignore the first line of code 3, the rest of the view contains the standard HTML. You can type any HTML you want to modify the contents of the view.

Views are similar to pages in ASP or ASP.NET Web forms. Views can contain HTML content and scripts. You can write scripts in your favorite programming language (for example, C # or Visual Basic .NET). Use scripts to display dynamic content, such as database data.

Understanding model

We have discussed controllers and views. The last topic is the model. What is the MVC model?

The MVC model contains all the logic in the program, which is not included in the view or controller. The model should contain all program business logic, validation logic and database access logic. For example, if you use Microsoft Entity Framework to access the database, you need to create an Entity Framework class (.edmx file) in the Models folder.

The view should contain only the logic for generating the user interface. The controller should contain only minimal logic to return the correct view or redirect the user to another action (flow control). Everything else should be included in the model.

In general, you should work hard for "fat" models and "thin" controllers. The controller method should contain only a few lines of code. If the controller action becomes too fat, you should consider moving the logic out to a new class in the Models folder.

These are all the contents of the article "sample Analysis of models, views and controllers in C#". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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

Development

Wechat

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

12
Report