ASPnet mvc4 go
-- I admit that I am very lazy, but today I may be able to "meow" something
Original: ASP. net mvc 4 in action
I have limited ability. I try to concentrate on the knowledge in the book. After careful study, you will learn about the MVC Framework in other languages.
ASP. net mvc compared to webform, after completing chapter 1, you will find that the browser address bar is so concise and the file classification is so well maintained,
Without a master page, you can write functions similar to templates.
What this contact is about:
Sqlserver compact (SSC for short)
Controller, which contains multiple actions (I call it)
View"
Razor (one type of view engine), which is short for me, is a web page label, another programming style, and another writing method.
Route (route), I hate it, because it is too abstract and can be understood for the moment. After a URL is entered in the address bar of a browser, press enter to process it and then jump to it, at present, I understand such a technology
Viewbag: a dynamic object. You will understand its role through a project. Baidu C # dynamic can be understood now
Understand the dynamic keywords in C #4.
1. Establish the environment
In this example, the ultimate version of vs2012 is used. The ASP. NET mvc4 plug-in can be installed in vs2010. Chrome 23.0.127.1.1 is selected in the browser, and C # is selected in the background language #
2. Create a folder E: \ myaspnetmvc4 \ Users
Create a project guestinfo
Select razor as the default view engine. You do not need to select create unit test project. Click OK.
Wait for the completion of the project...
The default project structure created by vs2012 is as follows:
App_data: Put some database files, XML files, or other files needed in our project, Asp. this special directory can be identified during the net runtime, so users can avoid direct access to this directory, only our applicationsProgramAble to read and write this directory
Content: contains some non-CodeResources, which usually contain image files and CSS files, including a site.css style sheet and a themes folder. We can see that we are familiar with the jquery UI Library (which should be known for web development)
Controller: the controller is an intermediary class that processes user requests and determines which page (View) to return. In ASPnet MVC, the controller is all in this folder. By default, there are two controllers, homecontroller (processing requests on the home page) and accountcontroller (processing permissions)
Images: puts some image resources
Models: place our object classes. As our projects become larger and larger, for example, we may move the classes in the object class folder to a specialized class library, just like the entity layer on the third layer. accountmodels is included by default. CS class
Scripts: contains some JS files that we may use.
View directory: contains a template that shows the project interface you used in the project. Each template is displayed in the razor view (cshtml file or vbhtml file ), these files can be created from the Controller in the Controller directory or manually. After the meeting, we will study the relationship between controller, actions, and views.
Global. asax: when your project is running, it initializes some code, such as registering a route using code
Web. config: sometimes some configuration details are necessary to ensure that ASP. net mvc programs can run smoothly.
Run the project by pressing F5. The following interface is displayed, indicating that the development environment is successfully set up!
Preliminary Exploration of ASPnet mvc4 Project
--This project is boring, but I will go down
2.1 Basic Concepts
Controller is the parent class of all controllers.
After viewbag, I can define any name attribute, because viewbag is a dynamic data type, similar to JavaScript var. during runtime, judge the type, and then create, C # Why is this syntax true in 4.0?
Homecontroller inherits the controller and owns everything. Even the suffix of the Class Name (suffix) has the Controller as the annotation.
Each access modifier is public, and the returned value is a view () in the actionresult method. This method is defined in the parent class of controller.
Now we place the cursor on the method name, right-click
In fact, view is really uncomfortable. How nice is the page?
By the way, you may also find that the view is in the razor style and the suffix is cshtml. In the past, webform, each ASPX page has An ASPX. CS post-code processing file. ASP. NET consists of two parts: processing in the Controller and writing in cshtml. The @ symbol is used to differentiate between them, a bit like JSP.
Go back to the Controller folder. What is that? Go to homecontroller.
In this controller, three actions are defined, named index/home/contact.
Okay, the point is.
First understanding (simplified browser address bar ):
Because these three actions are defined in the homecontroller controller (actually a class that inherits the Controller), each action returns a view type ~ I'm going crazy, God. Forgive me. Could you just say that?
Each action returns a page type ~ More comfortable, return a page, return view ()
Therefore, you can go to the address bar of the browser: http: // localhost: Port Number/controller name (after the Controller suffix is removed)/then the method name of the return value type of actionresult, for example: http: // localhost: 5438/home/index. You can right-click the actions name and choose to go to the view page.
This is the page views/home/index. cshtml, but it is not displayed in the address bar.
You may ask why?
I think if you can find the page to be displayed based on this URL, you will understand
For example, for a default template (homecontroller. CS ):
Here we add an action
Public actionresult testha (){
Viewbag. Message = "ala just wants to test ";
Return view ();
}
Right-click a method name and add a view. A dialog box is displayed. Keep the default value. Click Add.
Generate a testha. cshtml file in the views/home directory.
The name of the cshtml file. testha is the name of this action.
The name of its directory, home, is the controller of the corresponding action. homecontroller removes the name of the controller suffix.
Verify your questions again
Right-click the Controller folder and add a new controller named guestbookcontroller. CS.
In the file, we create an action called create
Public actionresult create ()
{
Return view ();
}
Right-click the method name to add the view, and find that there is an additional create. cshtml file named after the corresponding action, and the directory is Guestbook
In fact, the name of the cshtml file corresponding to the action cannot be the same as the method name.
Now, you can find the corresponding page for this URL.
Well, the computer can identify it, mainly because the file global. asax contains a registerroutes method.
Let's take a look. Open the global. asax file, place the cursor in the registerroutes method, and press F12 to go to the corresponding definition.
We can see that two entries are defined here)
First, ignoreroute tells the framework not to worry about matching some special URL paths. In this example
Do not process any file requests ending with. axd, such as trace. axd.
Second, maproute defines how the URL is processed. The default routing configuration code can help some applications complete the configuration.
But in the future, you may add more routes because some special URLs are used in your application to solve these special routing problems.
We keep the default value temporarily
We can see that each route has a name, URL definition, and an optional default value. Sometimes, when our program runs for the first time, there is no URL segment, such as home/index. Directly use a domain name or the localhost: port number during testing. The program loads the default page according to the default value.
In the default settings, you can see that the translated URL is/home/index, which is the default one. The parameter ID is optional.
It is because of this default value that
In the address bar, assume that your domain name is mysite.com.
You can directly enter the http://MySite.com or enter http://mysite.com/home/index#http://mysite.com/home
Can trigger the index action in the homecontroller class, and then load the effect of views/home/index. cshtml.
An episode about route
URL parameter URL: "{controller}/{action}/{ID }"
Obviously, we can see that all of them are enclosed in braces {}. This default URL template is a common route that can serve many Web requests, the word MVC Framework in brackets can be understood. The most common words are controller and action.
Next let's take a look at the interesting viewbag. I personally think it is fun.
Go back to homecontroller. CS and open the file.
Write a test, and you will say, oh! Sodexon (Japanese: It turns out so)
Add a line of code in the index action, viewbag. currentdate = datetime. now;
If you know about the C # dynamic type, it's too simple.
Both currentdate and message attributes are not in viewbag, so you can change the currentdate name to any one, such as hahadate.
Message can also be changed. Of course you can also define several other variables. You can rest assured that it will be useful later. for example, here we use currentdate. As you can see, it is of the datetime type. Dynamic type. You can compare it with Js. When you write JavaScript, the program does not know what type it is. When the program is running, it judges it by itself and then creates an object, the name is the one you defined.
After currentdate is defined, we can use the currentdate variable in the view corresponding to the action. Then, of course, this value can be displayed on the page.
Go to the page (View) corresponding to the index action under homecontroller ----------- (forgive me, I swear this is the last time I write the view)
As shown in the following figure, the C # code and HTML Tag page is similar to JSP, PHP, and ASP.
Add the following code after
<P> current time: @ viewbag. currentdate. tolongdatestring () </P>
Run the program by pressing F5. The effect is as follows:
I guess you already know the first usage of viewbag.
In this cshtml, ASP. net mvc uses the @ symbol to complete a transition between HTML tags and C # code.
Homecontroller shows the basic use of controllers and views in MVC applications, but it is not interesting to display a simple text on the screen.
In the last phase of this chapter, we will create a simple guestbook project for data entry and presentation, as an introduction to ASP. NET mvc4.
GuestbookASPnet mvc4I'm coming
--I have already prepared it. Let's get started! Excited
3.1 database, sqlserver compact
SSC is a relational database that Microsoft has added to the sqlserver family. It is a lightweight database that can be used in desktop program development, web development, and even Windows Phone applications, it does not need to be installed or any service is started to help it run. In the past, when we were using sqlserver, we had to start services or something, such as net start MSSQLServer.
If you have used an Access database, you can imagine that SSC is like access. Instead of starting the service or installing anything, it can be used as a medium to store the data required by our program.
Right-click the app_data folder and choose add> Create item.
Manually create a database, create a table, create fields, and then use them for the program.
In this example, we use code to create a database, instead of manually adding a database.
3.1 start
3.1.1 create an object in the models folder.
The Code is as follows:
Public class guestbookentry
{
Public int ID {Get; set ;}
Public string name {Get; set ;}
Public String message {Get; set ;}
Public datetime dateadded {Get; set ;}
}
The names of these four attributes are best the names of the columns in the final database table. It is best to match them. You will know it later. This is just a trick.
Now we only use a class to represent a table in the database.
But how do we map objects to tables in the database? Or convert the data in the database to an object?
Here we need to use the ORM tool. If the ORM doesn't understand it, don't be too nervous.
In this example, entity framework4.1 will be used for this ing. Although in. there are a lot of ORM tools on the net platform for us to choose (in the following chapters, we will take a look at some ORM tools in nhib.pdf), and EF is a large Orm, there are several books dedicated to it, but entity framework4.1 provides some simple APIs, we will use a very simple way to use EF to complete the database access of our project. So don't worry
Before using EF, we need to add a dbcontext class for our application. In Entity Framework, the dbcontext class provides some abstract methods to help us persist data and read data.
Now we add a guestbookcontext class under the models folder and let it inherit dbcontext and quickly import the namespace by SHIFT + ALT + F10
Public class guestbookcontext: dbcontext
{
Public guestbookcontext (): Base ("Guestbook "){}
Public dbset <guestbookentry> entries {Get; set ;}
}
An episode about Data Access choice
In. NET development, there are many choices when processing data access. Currently, many modern applications use Entity Framework or nhib.pdf as ORM tools to process relational databases, but not every project needs to use them. We can choose other projects.
If your application is small, you may decide not to use that complicated Orm. You can use webmatrix. Data or simple. Data in your project to meet your needs.
Webmatrix. datashi as ASP. net web page processing technology product series, in ASP. net mvc3 was released together. It provides a lightweight, data access using pure SQL statements and dynamic type Syntax of DLR. Simple. data provides a simpler solution, which relies on dynamic query syntax instead of SQL statements. For more information about simple. Data, visit https://github.com/markrendle/simple.data.
Dbcontext (dependent on system. data. entity namespace) class, we passed a guestbook parameter in its constructor, because our database name is called guestbook. SDF. If we do not pass the parameter, EF will generate a guestbookcontext based on the class name. databases like SDF
This class also defines an entries attribute of the dbset <guestbookentry> type. It plays a role in querying data from the guestbookentry table and returns a set of objects that read data to the memory.
On this basis, Entity Framework will generate appropriate SQL statements to query this table, and convert the query results to a strong type of guestbookentry object. We will query this set later. Finally, we need to make the EF and SSC communicate
Generate database from Model
There are many ways to achieve this. We can manually add some code to application_start in the global. asax. CS file to do some work. This is a special method. When we run the program, it will be called immediately.
However, to achieve this goal, we can use a method slightly different from this-we can use the nuget package to complete some initialization work for us.
Nuget is a package management tool that can easily and quickly add some open-source class libraries to our. Net project. Although nuget is not bundled in ASP. net MVC project, but it is installed in your asp. net MVC environment has been installed together, so you do not have to install it separately, you can directly use it.
Open the manage nuget package menu, enter entityframework. sqlservercompact to find and install this open-source class library.
We can also useWebactivatorTo register some start code, more information: https://bitbucket.org/davidebbo/webactivator
Now, add a guestbookcontroller. CS controller to the Controller folder.
There are many templates below. We will use the default templates. For more information, see
Open guestbookcontroller and add an action named "CREATE", as shown in figure
Press F5 and enter http: // localhost: Port/guestbook/create in the address bar. An error is returned because the corresponding view cannot be found.
In this error, we found that it is in the guestbookcontroller where the create action is located, and uses guestbook as the subdirectory in the Views directory to start searching for create. aspx, create. ascx (this is because of other view engines) and create. cshtml (C # language version) and create. vbhtml (VB.. Net version). If the corresponding controller cannot be found in the directory named directory, it will find it from the views/shared directory, the shared view is shared by multiple controllers (page)
Now we can manually right-click the views directory, manually add a view, or right-click the action name of the Controller to add a view that is the same. You can choose either of them.
After creating create. cshtml,
We add the following code. To avoid code Pasting and copying without thinking, I will map it.
Okay. Press F5 to start running. in the address bar, manually enter http: // localhost: Your port number/guestbook/create
Note: In this form, there are two inputs: name and message. These two names are actually skillful. They correspond to the attribute names in the guestbookentry object we define, later, let's take a look at how they are automatically bound.
This new create action can be accessed at/guestbook/create "> http: // localhost: <port>/guestbook/create
It is necessary to add an action in guestbookcontroller to process the form POST request and add a data entry to the database.
To do this, we will use the previously created guestbookcontext class and guestbookentry entity class in the models directory.
Now we add a create with parameters to guestbookcontroller. The Code is as follows:
We have reloaded the create method and added an httppost feature to indicate that this method can only be accessed by http post requests.
We will study this in depth in the future.
This method has a guestbookentry type parameter. The attributes of this object are automatically bound to our form page because the element names in the form are the same as those in the object.
Savechages () is to write our data into the database
I don't want to talk about EF here. In fact, I wrote a very common savechanges () method, no matter whether you modified the data, added the data, deleted the data or something, there was no impact on the database at that time. Only when you call the savechanges () method can you submit all your data operation statuses to the database and complete a "synchronization" operation"
Some databases use the same syntax. After writing an SQL statement, you have to write a submit statement.
Press F5 to open the create page and submit the input data. The data can be successfully added.
Adding data in light is useless. We don't know if the data is actually added, so we need a page to display the message.
The default controller has an index action. Now we add the following code to extract only the 20 most recently added data records from the guestbookentry table.
EF, which uses the LINQ-style syntax. If you want to learn EF, you should first learn LINQ.
Here we only follow the descending order of dateadded, and then we can get the latest 20 recently added records, and then display them on the page. We put this object in viewbag, in this way, we can use the 20 records we have obtained on the page, and then we can use the for loop to demonstrate
After a message is created, it is recommended that you return to the display page. Currently, we only prompt that the message is successfully added.
Modify the create method with parameters as follows:
We use the redirecttoaction method. This method can help us to automatically call the index action in this controller after it is successfully added.
Now, add the corresponding View to the index in the Controller (well, I admit it ~ Page)
Modify the corresponding index. cshtml. The Code is as follows:
Now we have done most of the work.
Press F5 to run it. Enter/guestbook/create "> http: // localhost: <port>/guestbook/create in the address bar of the browser.
So far, we should have a rough understanding of MVC. By the way, it is so simple.
But we are not finished yet.
Now, let's modify the appearance to understand layout.
We entered the address bar manually each time.
So let's take a look at the layout of mvc4, not Div + CSS or template page, but the idea of Template
In fact, the page we are currently looking at is actually a combination of pages, similar to the template page, some places empty, for content page filling or something
If you are using the previous ASP. net mvc or ASP. NET webform, this layout is like the master page you are using.
Now let's open layout and add a menu to jump to guestbook/index. cshtml.
Open it in the views/shared directory.
The actionlink method has three parameters (the displayed text, action name, and controller name), which are similar to the functions of hyperlinks in HTML tags.
We changed the text "place your logo here" to "my guest book"
In this file, we also find several other interesting parts, such
AboutPartial ViewWe will explain it in the next chapter, but its final role is to re-use part of HTML in a page composed of multiple pages.
For the menu, it selects a <ul> unordered list tag, and we add a link to view the message. The Code is as follows:
The last interesting thing is the renderbody method.
The original Article is explained as follows. I don't know what I'm talking about, right?
This method will add some content to the current view (_ layout. cshtml), which is written by the action
The HTML code generated by the view is wrapped in layout, which is in <section class = "content-wrapper main-content clear-fix"> </section>.
Summary:
This chapter is about ASP. net MVC programming Step 1: we created a new project and started to study the various parts of the default Project template. We talked about the concept of controller, we further talked about the Controller class andThe action method, then we see how the razor template is displayed as a view (PAGE), and how the route maps the request URL (mapping, of course, we can also create a special custom URL template by ourselves. The details will be explained in chapter 9th.
On this basis, we created the guestbook example to verify our ideas-we used the Entity Framework dbcontext API and SQL Server compact to add and query data, we also quickly added additional packages in our project using the nuget Package Manager
Finally, we used layout to complete the unified style interface and felt that multiple views are in a Single View File (PAGE). This is a good transition to the next chapter, in the next chapter, we will continue to use the razor view in the guestbook application, and will continue to explain detailed knowledge points using this project.
This chapter source code: Download http://download.csdn.net/download/yangyanghaoran/5043248
The directory addresses of ASP. NET mvc4 in Action series have been generated:Click to view the Directory