Java attack C # -- Application Development-Asp.net MVC,

Source: Internet
Author: User

Java attack C # -- Application Development-Asp.net MVC,

Summary of this Chapter

In the previous chapter, I talked about Asp. NET. After learning about the basic knowledge of Asp. NET, it is much easier to learn about the MVC Framework of C. This chapter introduces Asp. net mvc. I believe you are clear about the idea of MVC. I will not talk about it here. I have a classmate who developed Asp. NET. He told me a word-I almost forgot HTML. We know Asp. NET in the previous chapter. With pure HTML, I think you will be considered SB. Asp. net mvc won't disappoint anyone who prefers to write Interface Design manually. In this article, I may also use some struts2 framework knowledge to compare it. Not much. Go to the content of this chapter.

Global. asax File

Let's take a look at the next file before talking about Asp. net mvc. Is the Global. asax file. So why should we talk about this file? What is the role of this file? The full name of the Global. asax file is the Global application class. It has no direct relationship with Asp. net mvc. Asp. NET is often used. It is also easy to create. Right-click the project and choose add> new item.

Click Add button:

Double-click Global. asax:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Security;using System.Web.SessionState;namespace WebExample{    public class Global : System.Web.HttpApplication    {        protected void Application_Start(object sender, EventArgs e)        {        }        protected void Session_Start(object sender, EventArgs e)        {        }        protected void Application_BeginRequest(object sender, EventArgs e)        {        }        protected void Application_AuthenticateRequest(object sender, EventArgs e)        {        }        protected void Application_Error(object sender, EventArgs e)        {        }        protected void Session_End(object sender, EventArgs e)        {        }        protected void Application_End(object sender, EventArgs e)        {        }    }}

Read the above Code. I believe that only one or two names can be seen from the name. What does it mean? The Application_Start method is called only once when the application starts execution. In each request, the Application_BeginRequest method is called. When the application is closed, Application_End is called. If I do not know the Session for B/S development, I cannot do anything about it. So I will not talk much about the Session_Start method call. Does JAVA have something like a Web. xml listener.

Asp. NET MVC

I learned Asp. NET MVC. The Asp. net mvc example of visual studio has made great contributions to the author. Let's take a look at the columns of visual studio to learn about Asp. net mvc. Create a project. I don't need to talk about it. Let's take a look at the new project dialog box.

After confirming. The following dialog box is displayed.

 

We can see multiple options above.

Null: creates an Asp. net mvc with nothing.

Basic: Create an Asp. net mvc that can be basically developed.

Others: Examples for different businesses.

I chose Internet applications to learn about Asp. NET MVC. The following figure shows the new project structure.

App_Data Folder: used to store data files. For example, the MDF file of SQL server is similar.

App_Start Folder: this folder stores some configuration classes to be executed when Asp. net mvc starts.

Content Folder: stores some theme files. Such as CSS files.

Controllers Folder: stores Controllers. That is, C in MVC

Filters Folder: you can find the filter by name.

Images Folder: no more. Store images.

Models Folder: used to store model objects.

Scripts Folder: used to store JS files.

Views Folder: used to store Views.

With the column created above. This is quite a good thing for me. The author knows at least one thing based on the above project structure. V in MVC is in the corresponding Views folder, and C is in the Controllers folder. This is important to us. The next step is to understand how M-V-C works. We can learn Asp. net mvc. Struts2 loads the corresponding configuration file at startup. Of course, for Asp. net mvc, there is also a corresponding job. The loading is different. As follows.

Global. asax:

 public class MvcApplication : System.Web.HttpApplication    {        protected void Application_Start()        {            AreaRegistration.RegisterAllAreas();            WebApiConfig.Register(GlobalConfiguration.Configuration);            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);            RouteConfig.RegisterRoutes(RouteTable.Routes);            BundleConfig.RegisterBundles(BundleTable.Bundles);            AuthConfig.RegisterAuth();        }    }

The above code is in the Global. asax file. So where can I tell you? This is where Asp. net mvc is initialized. How many things have been done above?

1. Register WebApi. What is WebApi. I wonder if you have used the RESTful framework. It's a pity that I only understand it.

2. register the filter. JAVA developers do not know the filter. That's too much.

3. register the vro. This is important. What is Struts2 like? Use the requested URL to find the corresponding Action class. No error. It must be through the action node of the struts. xml configuration file. The router is equivalent to the action node function.

4. Register Bundle information. I cannot say anything about Bundle. I only know that it is used to introduce CSS and JS on the UI interface. At this time, you can bind multiple CSS and JS together. As long as a Bundle URL is introduced, this CSS and JS will be introduced together.

5. register the certificate. For this. Read this information by readers. I have never used it. So I dare not say it.

From the above, we know that the request URL is analyzed by the router to find the corresponding controller. Therefore, to learn Asp. net mvc, you must understand what the router looks like. Let's find a class named RouteConfig in the App_Start folder. As follows:

 1 public class RouteConfig 2     { 3         public static void RegisterRoutes(RouteCollection routes) 4         { 5             routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 6  7             routes.MapRoute( 8                 name: "Default", 9                 url: "{controller}/{action}/{id}",10                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }11             );12         }13     }

The above is where the router is configured. We can see that the router is actually a method to set a URL template to process the corresponding URL request. The above is the default URL template provided by Asp. net mvc.

Name: name of the current vro.

Url: URL template.

Defaults: the default value of the URL request.

This is different from Struts2. In processing URL requests, Struts2 determines the corresponding action class by the name of the package node and the name of the action node, and then executes the corresponding method through the action node configuration information. Asp. net mvc analyzes and finds the corresponding methods in the Controller and controller through the router. What is it like? Let me take a look at the above url value.

"{controller}/{action}/{id}"

The above is the URL template. Assume that the user requests http://xxx.xx.com.cn/aomi/index/7. Refer to the template above. We can know that the controller value is aomi, the action value is index, and the id value is 7. Here id is an optional value. What do you mean? Have you seen id = UrlParameter. Optional? Id is optional. Therefore, strictly speaking, the function of the action node corresponds to the Controller of Asp. net mvc. Is used to control the view to be displayed after the business ends. The difference is that the controller is a class. Let's take a look at the Controller code. This enhances understanding.

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MvcExample.Controllers{    public class HomeController : Controller    {        public ActionResult Index()        {            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";            return View();        }        public ActionResult About()        {            ViewBag.Message = "Your app description page.";            return View();        }        public ActionResult Contact()        {            ViewBag.Message = "Your contact page.";            return View();        }    }}

The HomeController class inherits the Controller class. Do you want to inherit the Controller class. Obviously not. I tried to remove the Controller behind HomeController and found that no Controller was found. It indicates that Asp. net mvc still has a Convention-the Controller should be named by XxxController. Can't developers define their own names? I did not say no. It's just a bit annoying. He needs to use the Controller factory. That is, IControllerFactory. So I hope you can be honest. After the business ends, struts2. Returns a string to determine the view to be displayed. Struts2 has several views. In the same way, Asp. net mvc also has several returned results.

EmptyResult: returns an empty result. The return value is void.

ContentResult: returns the result of a text.

JsonResult: return a result in JSON format.

ViewResult: returns the result of a view. It is similar to HTML files.

Not all of them are listed above. In other words, I hope readers can view the information on their own. Okay. Let's take a look at the View () method in the code above. This returns a ViewResult type class. The preceding command only calls View (). At this time, he will use the method name to determine the corresponding view. For example, the index method is called. View () will go to the Home folder under the Views folder to find Index. cshtml. So why is the Home folder? By default, if XxxController is used, it is the View under View/Xxx. So what is a cshtml file? You can understand that the ftl file is of the same type. At the same time, there is a Shared folder under the Views folder. As follows.

Each controller has a corresponding folder in the Views folder. The folder name is the same as the controller name. Are there any shared items? No error. Shared Folders are used for all controllers. Now there is only one problem-use other views. View the following picture in the screenshot.

If we call the Index method. In principle, we need to call Index. cshtml. If you want to call Aomi. cshtml. As shown in the following figure.

 public class Home:Controller    {        public ActionResult Index()        {            return View("Aomi");        }    }

We all know how the Controller goes to view. Let's take a look at the value transfer from the View to the Controller and the value transfer from the Controller to the View.

1. Pass the View value to the Controller. There are two types. One is to use model objects for transmission. One is KEY-VALUE. However, make sure that the Name of the form element corresponds to the parameter Name. Is the same.

2. Pass the value from the Controller to the View. There are generally three types. Use ViewBag to pass the value. Use Model to pass the value. It is the model object. ViewData is also used.

I have added a method named Aomi. The parameter is name. And upload it to the view through the dynamic ViewBag. And displayed.

Controller:

 public class Home:Controller    {        public ActionResult Index()        {            return View("Aomi");        }        public ActionResult Aomi(string name)        {            ViewBag.Name = name;            return View("Aomi");        }    }

View:

@{    ViewBag.Title = "Aomi";}

Execution result:

Note: The name must be the same as that of the parameter. Otherwise, it cannot be passed.

The author briefly explains the problem of passing values. Now let's take a look at the knowledge used in the view. Asp. net mvc views generally use the razor engine. Therefore, it is important to learn the razor syntax. There are many razor syntaxes on the network. I will not talk much about it. I will give a simple example.

    public class HomeController : Controller    {        public ActionResult Index()        {            return View("Aomi");        }        public ActionResult Aomi(string name)        {            ViewBag.Name = name;            return View("Aomi");        }        public ActionResult Show()        {            ViewBag.DataList = new List<string>() { "a", "b", "c" };            return View();        }    }

Show. cshtml:

@{    ViewBag.Title = "Show";}@foreach (string val in ViewBag.DataList){    <b>@val</b> }

Execution result:

In fact, learning Asp. net mvc is not difficult. I believe that enterprise development has no major problems as long as I master several points.

1. Understand the router usage.

2. How to transmit values between View and Controller.

3. How does the Controller determine the View.

4. The last step is to learn the razor syntax.

Summary

This chapter describes Asp. net mvc. Describes how to transmit values between a vro and a view and a control. It can be said that this is the focus. So this series is here. This series is not intended for teaching. It is a guide. This is a process when I learned C # In my years. Finally, thank you.

Related Article

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.