ArticleDirectory
- 1.1 preparations
- 1.2 create an ASP. net mvc Web Application Project
- 1.3 create a controller
- 1.4 create a view
- 1.5 create a database
- 1.6 create a model
- 1.7 add database logic to the Controller Method
- 1.7 modify the index View
- 1.8 conclusion
From Zhang Ziyang: http://www.cnblogs.com/JimmyZhang/archive/2009/01/01/1366473.html
This tutorial aims to show you how to create an ASP. net mvc application.Program. In the tutorial, I quickly created a complete ASP. NET application from the beginning to the end. I showed you how to create a simple task list application.
If you have used Dynamic Server Pages (ASP) or ASP. NET, you should find ASP. net mvc very familiar. ASP. net mvc views are very similar to pages in ASP. And, just like a traditional ASP. NET web form application, ASP. net mvc provides you with full access to a wide range of languages and class sets provided by the. NET Framework.
I hope this tutorial will give you the feeling that creating an ASP. net MVC application process and create an ASP or ASP.. NET web forms applications are similar and different.
1. Task List Application
For simplicity, we will create a very simple task list application. Our simple task list application will allow us to do the following three things:
- List task sets
- Create a new task
- Mark a task as completed
Similarly, for simplicity, we use the minimal number of ASP. net mvc frameworks required to create applications. For example, we will not use test-driven development or HTML Help methods.
1.1 preparations
To create an ASP. net mvc application, you need Visual Studio 2008 or visual web developer 2008 Express. You also need to download the ASP. net mvc framework. If you do not have your own Visual Studio 2008, you can download a 90-day trial version of Visual Studio 2008 from this site:
Http://msdn.microsoft.com/en-us/vs2008/products/cc268305.aspx
In addition, you can use Visual Web Developer express 2008 to create an ASP. net mvc application. If you choose to use visual web developer Express, you must install Service Pack 1. You can download Visual Web Developer express 2008 and Service Pack 1 from the following sites.
Http://www.microsoft.com/downloads/details.aspx? Familyid = BDB6391C-05CA-4036-9154-6DF4F6DEBD14 & displaylang = en
After Visual Studio 2008 or visual web developer 2008 is installed, you must install the ASP. net mvc framework. You can download the ASP. net mvc framework from the following website:
Http://www.asp.net/mvc/
1.2 create an ASP. net mvc Web Application Project
Let's create a new ASP. Net MVC web application project in Visual Studio 2008. Select the menu options, "file" and "New Project", and then you will see the new project dialog box, as shown in 1. Select your favoriteProgramming Language(Visual Basic or Visual C #), and select ASP. net mvc web application project. Name the project tasklist and click "OK.
Figure 1. New Project dialog box
Visual Studio will ask you whether to create a separate unit test project whenever you create an MVC web application project. The dialog box shown in Figure 2 appears. Because of the time limit, we do not want to create a test project in this tutorial (yes, we should feel a bit embarrassed). Select the "no" option, click OK.
Figure 2. Create a unit test project dialog box
An ASP. net mvc application has a series of standard folders: models, views, and controllers. You can see these standard folders in the solution browser window. We will need to add files to models, views, and controllers to create our tasklist application.
When you use Visual Studio to create a new MVC application, you will get a sample application. Because we want to start from scratch, we need to delete the content of this sample application. You need to delete the following files and folders:
- Controllershomecontroller. CS
- Viewshome
1.3 create a controller
Typically, when we create an ASP. net mvc application, you start by creating a controller. Each request to an ASP. net mvc application is processed by a controller. A controller contains the application logic that responds to a request.
Right-click the Controller folder and select "add" and "new item" from the menu )", add a new controller to your Visual Studio project. Select the "MVC controller class" template. Name your new controller homecontroller. CS and click "add.
For our task list application, we modify the homecontroller class to includeCode. The modified controller contains four methods: Index (), create (), createnew (), and complete (). Each method corresponds to the action of a controller.
Code List 1-homecontroller. CS
UsingSystem;
UsingSystem. Collections. Generic;
UsingSystem. LINQ;
UsingSystem. Web;
UsingSystem. Web. MVC;
UsingTasklist. models;
NamespaceTasklist. controllers {
Public Class Homecontroller:Controller{
// Display the task list
PublicActionresult index (){
ReturnView ();
}
// Display a form for creating a new task
PublicActionresult create (){
ReturnView ();
}
// Add a new task to the database
PublicActionresult createnew (){
ReturnRedirecttoaction ("Index");
}
// Mark a task as completed
PublicActionresult complete (){
// Code: Database Logic
ReturnRedirecttoaction ("Index");
}
}
}
Here is the intent behind these controller actions:
- Index ()-called when you want to display a task list.
- Create ()-called when you want to display a form for adding a new task.
- Createnew ()-called when the form for adding a new task is submitted. This controller action actually adds a new task to the database.
- Complete ()-called when a new task is identified as completed.
We need to add additional logic to our controller actions so that they can work as expected.
Any public methods contained in the Controller class are exposed as controller actions. Note here. A controller action is exposed to the world. Anyone can call the Controller action by entering the correct URL in the address bar of the Web browser. Therefore, when you do not need to call a method, do not create a public method in the Controller at will.
Note that the controller action returns an actionresult. Actionresult indicates the action to be completed. The first two controller actions, index () and create (), return an MVC view. The result of the third and fourth actions is to redirect the user to another controller action.
This is how these controller actions work. When you request the CREATE () controller action, a view is returned, which contains a form used to create a new task. When you submit this form, the createnew () controller action will be called. The createnew controller action adds a new task to the database and redirects the user to the index () controller action. The index () controller action returns a view that shows the complete task list. Finally, if you identify a task as completed, the compete () controller action is called and the database is updated. The complete () controller redirects the user back to the index () action and displays the updated task list.
1.4 create a view
The view contains HTML tags and content sent to the browser. In ASP. net mvc applications, the view is most similar to the page. You can create a view by creating a file with the suffix. aspx.
You must place the view in the correct position. If you are creating a view for the index () Action Method of homecontroller, You must place the view in a folder conforming to the following path:
Viewshomeindex. aspx
If you are creating a view using the productcontroller price () Action method, the view must be placed in the following folder:
Viewsproductprice. aspx
By default, the view should have the same name as its corresponding controller action. The view should also be placed in a folder that corresponds to the Controller name.
You can create a view by right-clicking the subfolders in the Views folder and selecting "add" and "new item" from the menu. Select the "MVC view page" template to add a new view. We need to create two views in the following path:
Viewshomeindex. aspx
Viewshomecreate. aspx
After you have created these two views, your solution browser window should contain 3 files:
Figure 3. Index. aspx and create. aspx views
A view can contain HTML content and scripts. The index. aspx view is used to display the list of all tasks. To illustrate this view, add the code in Listing 2 to the index. aspx view.
Code List 2-index. aspx
<% @ Page Language = "C #" autoeventwireup = "false" codebehind = "index. aspx. cs" inherits = "tasklist. Views. Home. Index" %> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml">
<Title> </title>
</Head>
<Body>
<Div>
<H1> my tasks
... Displaying all tasks
<A href = "/home/create"> Add new task </a>
</Div>
</Body>
</Html>
Now the index. aspx view does not display any tasks-it just declares that it will be displayed. After this tutorial, we will add some scripts for the index. ASPX page to display the task list.
Note that the index. aspx view contains links marked as "Add new task. This link points to the/home/create path. When you click this link, the CREATE () Action of homecontroller will be called. The create () method returns the create view.
The create. aspx view contains a form for creating a new task. The content of this view is included in listing 3:
Listing 3-create. aspx
<% @ Page Language = "C #" autoeventwireup = "false" codebehind = "Create. aspx. cs" inherits = "tasklist. Views. Home. Create" %> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Div>
<H1> Add new task
<Form method = "Post" Action = "/home/createnew">
<Label for = "Description"> task: </label>
<Input type = "text" name = "Description"/>
<Br/>
<Input type = "Submit" value = "add task"/>
</Form>
</Div>
</Body>
</Html>
Note that the forms in listing 3 are submitted to the following URL:
/Home/createnew. aspx
This URL corresponds to the createnew () action in the homecontroller controller. The form data of the new task will be submitted to this action.
1.5 create a database
The next step is to create a database with tasks. You can right-click the app_data folder and select the menu items, "add" and "new item" to create a database. Select the "SQL Server database" template item, name the database tasklistdb. MDF, and click "add.
Next, we need to add a table containing tasks to the database. In the solution browser window, double-click tasklistdb. MDF to open the server browser window. Right-click the "table" folder and select the "Add new table" menu item. Select this menu item to open the Database Table Designer. Create the following database columns:
Column name |
Data Type |
Whether null is allowed |
ID |
Int |
False |
Task |
Nvarchar (300) |
False |
Iscompleted |
Bit |
False |
Entrydate |
Datetime |
False |
The first column, ID column, has two special attributes. First, you need to mark the ID as a primary key column. After selecting the ID column, click the "Set primary key" button (which looks like a key icon ). Step 2: Mark the ID column as the identity column ). In the column attributes window, scroll down to the "Identity specification" section and expand it. Change "is identity" to "yes. After you finish these steps, table 4 is displayed.
Figure 4. Tasks table
The last step is to save the new table. Click "save" and name the new table tasks.
1.6 create a model
An MVC model contains most of the logic for accessing your applications and databases. Generally, you can put most classes in the MVC application in the models folder. The logic of view or controller contained in your application is pushed to the models folder.
In this tutorial, we will use LINQ to SQL to communicate with the database created in the previous section. For myself, I like LINQ to SQL. However, you do not need to use LINQ to SQL in ASP. NET MVC applications. If you want to, you can use other technologies, such as nhib.pdf or Entity Framework, to communicate with the database.
To use LINQ to SQL, we must first create our LINQ to SQL class in the models folder. Right-click the models folder, select the "add" and "new item" menu items, and select the "LINQ to SQL classes" template item. Name the new LINQ to SQL class tasklist. dbml and click "add. After you complete this step, the object relational designer is displayed ).
We need to create a LINQ to SQL entity class, which represents our tasks database table. Drag the tasks database table from the solution browser window to the object link designer. After the last action is executed, a new LINQ to SQL entity class named task will be created (see figure 5 ). Click "save" to save the new object.
Figure 5-task entity
1.7 add database logic to the Controller Method
Now that we have a database, we can modify our controller actions to store and retrieve tasks from the database. The modified homecontroller is included in Listing 4.
Listing 4-homecontroller. CS
UsingSystem;
UsingSystem. Collections. Generic;
UsingSystem. LINQ;
UsingSystem. Web;
UsingSystem. Web. MVC;
UsingTasklist. models;
NamespaceTasklist. controllers {
Public Class Homecontroller:Controller{
Private TasklistdatacontextDB =New Tasklistdatacontext();
// Display the task list
PublicActionresult index (){
VaRTasks = from tInDB. Tasks
Orderby T. entrydate
Descending select T;
ReturnView (tasks. tolist ());
}
// Display the form for creating a new task
PublicActionresult create (){
ReturnView ();
}
// Add a new task to the database
PublicActionresult createnew (StringDescription ){
TaskNewtask =New Task();
Newtask. Description = description;
Newtask. iscompleted =False;
Newtask. entrydate = datetime. now;
DB. Tasks. insertonsubmit (newtask );
DB. submitchanges ();
ReturnRedirecttoaction ("Index");
}
// Mark the task as a task
PublicActionresult complete (IntID ){
// Database Logic
VaRTasks = from tInDB. tasks where T. ID = ID select T;
Foreach(Task matchInTasks)
Match. iscompleted =True;
DB. submitchanges ();
ReturnRedirecttoaction ("Index");
}
}
}
Note that homecontroller in Listing 4 contains a class-level private field named dB. This dB field is an instance of the tasklistdatacontext class. The homecontroller class uses the DB field to represent the tasklistdb database.
The action of the index () controller has been changed to retrieve all records from the tasks database table. Tasks is passed to the index view.
The createnew () method is modified to create a new task in the tasks database table. Note that the createnew () method has been modified to accept a string parameter named description. This parameter represents the description text form field passed in by the create view. ASP. net mvc Framework automatically passes form fields as parameters to the Controller action.
Finally, the complete () method is modified to change the value of the iscomplete column in the tasks database table. When you mark a task as completed, the task id is passed to the complete () action and the database is updated.
1.7 modify the index View
To complete our tasklist application, we must do the last thing. We must modify the index view so that it can display the list of all tasks and allow us to mark a task as completed. The modified index view is included in listing 5.
Listing 5-index. aspx
<% @ Page Language = "C #" autoeventwireup = "true" codebehind = "index. aspx. CS "inherits =" tasklist. views. home. index "%> <% @ import namespace =" tasklist. models "%> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> index </title>
</Head>
<Body>
<Div>
<H1> my tasks
<Ul>
<% Foreach (task in (ienumerable) viewdata. Model)
{%>
<Li>
<% IF (task. iscompleted) {%>
<Del>
<% = Task. entrydate. to1_datestring () %>
-- <% = Task. Description %>
</Del>
<%} Else {%>
<A href = "/home/complete/<% = task. Id. tostring () %>"> complete </a>
<% = Task. entrydate. to1_datestring () %>
-- <% = Task. Description %>
<% }%>
</LI>
<% }%>
</Ul>
<Br/>
<A href = "/home/create"> Add new task </a>
</Div>
</Body>
</Html>
The index view in listing 5 contains a C # foreach loop that traverses all tasks. These tasks are represented by the viewdata. model attribute. In summary, you use viewdata to transmit data from the Controller to the view.
Inside the loop body, there is a condition to check whether the task has been completed. A completed task is represented by a strikethrough (strikethrough. The <del> tag in HTML is used to create a dash that crosses the completed task. If the task is not completed, a link marked as complete is displayed next to the task. This link is created by the following script:
<A href = "/home/complete/<% = task. Id. tostring () %>"> complete </a>
Note that the task id is included in the URL represented by the link. When you click the link, the task id will be passed to the complete () action of the homecontroller class. In this way, when you click the complete link, the correct database records will be updated.
The final version of the index view displays the page in figure 6.
Figure 6-index View
1.8 conclusion
The purpose of this tutorial is to allow you to experience the process of creating an ASP. net mvc application. I hope you will find that the experience of creating an ASP. Net MVC web application is very similar to that of creating a dynamic server page (ASP) or ASP. NET application.
In this tutorial, we only examine some of the most basic functions in the ASP. net mvc framework. In subsequent tutorials, We will dive into topics such as controllers, controller actions, views, View data, and HTML helper.