1. Use ASP. net mvc to create an applicationProgram
This articleArticleBy creating an Asp.net MVC application, it shows what Asp.net MVC looks like and shows us how to build a simple Asp.net MVC application.
If we have used ASP and Asp.net, we will be familiar with Asp.net MVC. From the perspective of page appearance, Asp.net MVC is more like ASP programs, and also like Asp.net traditional Web applications. Asp.net MVC provides complete multi-language functions and. NET Framework support.
In this article, we will understand the similarities and differences between Asp.net MVC applications and ASP and Asp.net traditional Web applications.
Ii. job list procedure
For the sake of simplicity, we will build a simple application here, which completes the following functions.
1. display the task list
2. Create a new job
3. Mark whether the job has been completed
For the sake of simplicity, we will do our best to use the new features of the Asp.net MVC framework (such as the test driver and HTML helper) in this project ).
3. Create an Asp.net MVC Web Application
In vs2008, click "file"-"New Project" to bring up the new project dialog box. Select ASP. net mvc web application, and write tasklist to the project name. Click "OK"
Figure 1
When creating an Asp.net MVC web application, Visual Studio prompts the following dialog box, prompting whether to create a unit test project. We do not want to create a unit test project here, So we select the "no" option and click "OK ".
Figure 2
ASP. net mvc applications have a series of standard folders:Models,ViewsAndControllers. In solution manager, we can see that we will add corresponding files to these folders to implement our applications.
When we use vs2008 to create a new ASP. net MVC application generates an example program. We can delete the relevant files and add our new files again. Here we will delete the two files in the following directory.
1. controllers \ homecontroller. CS
2. Views \ home
4. Create a controller
Generally, when we build an ASP. net mvc application, we build it from the Controller. Each browser request is sent to a controller in the ASP. net mvc program for processing. . The controller contains a series of program logic that responds to application requests. (CHE Yanlu)
To create a new controller, right-click the controllers folder in the solution and choose "add"> "Add new project ". In the displayed window, selectMVC controller class template And name the Controller file" Homecontroller. CS Click Add.
Here we modify the homecontroller class, Code The controller contains Four Methods: Index (), create (), createnew (), and complete (). Each method corresponds to a control action.
Listing 1-homecontroller. CS
Using system;
Using system. Collections. Generic;
Using system. LINQ; using system. Web;
Using system. Web. MVC;
Using tasklist. models;
Namespace tasklist. Controllers
{
Public class homecontroller: Controller
{
// Display a list of tasks
Public Actionresult Index ()
{
Return view ();
}
// Display a form for creating a new task
Public actionresult create ()
{
Return View ();
}
// Add a new task to the database
Public actionresult createnew ()
{
Return Redirecttoaction ("Index ");
}
// Mark a task as complete
Public actionresult complete ()
{
// Database Logic
Return Redirecttoaction ("Index ");
}
}
}
Index ()-display the list of all tasks
Create ()-when a new task is added, it is used to display the form.
Createnew ()-called when the form for adding a new task is submitted. This controller action actually adds the new task to the database.
Complete ()-call it to mark a task as complete .
Of course, we also need to add other logic to the Controller action to make the program work according to our intention.
The public method exposed in the Controller class is called the Controller action. HereNote that the action of the controller is exposed. Anyone can enter the corresponding path in the URL address bar of the browser to call the Controller action. Therefore, do not add public methods to the controller when we do not want the method to be called.
Actionresult data returned by the Controller action , Actionresult indicates how an action is operated. . In the first two actions (index () and create (), the MVC view is returned, and the third and fourth actions are directly redirected to other actions.
When we request create () to control the action, a form view containing the new task is returned. When submitting a form, call createnew () to control the action. createnew () adds a new task to the database and redirects it to the call to index () to control the action. The index () control action returns the view that displays the entire task list. Finally, when we mark a task as complete, the complete () action is called to update the database. After the complete () action is completed, the system redirects to the index () Action to display the update list. (CHE Yanlu)
5. Create a view
The view contains HTML tags and content sent from the server to the browser. A view is the closest to a page in an ASP. net mvc application. We create a view by creating the. aspx file.
We must clarify the position of the view. If we want to create a view for the index () action of the homecontroller controller, we must put the view in the following path:
\ Views \ home \ index. aspx
If you want to create a view for the price () action of the productorcontroller controller, the view must be placed in the following path:
\ Views \ product \ price. aspx
By default, the view should have the same name as the action corresponding to the Controller. The view must also be placed in a folder with the same name as the controller.
In solution manager, right-click the views folder and choose add> Add from the shortcut menu. Select the MVC view page template to add a new view. Create the following two view files.
\ Views \ home \ index. aspx
\ Views \ home \ create. aspx
When the two views are created, the following is displayed in solution Manager:
Figure 3
The view can contain scripts in HTML content, and the index. aspx view will be used to display the list of all tasks. The code for the index. aspx view is as follows:
Listing 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 ">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Div>
<H1> my tasks ... Displaying all tasks
<A href = "/home/create"> Add new task </a>
</Div>
</Body>
</Html>
The index. aspx view does not display any tasks currently. Here, it only declares that the task is being displayed. We need to add a script to display the task list in index. aspx.
The index. aspx view contains a hyperlink named "Add new task. This hyperlink points to the path "/home/create ". When we click this hyperlink, the CREATE () action of the homecontroller control class will be triggered. The create () method returns the created view.
The create. aspx view contains a new task form. The create. aspx code is as follows:
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 action submission direction of this form is:
/Home/createnew. aspx
This URL points to the createnew () action of the homecontroller controller. The form data will be submitted to this action.
6. Create a database
Next, create a task database, right-click the "app_data" folder, right-click "add"> "Add new project", select the data template item, and name the database tasklistdb. MDF, and click Add.
In solution manager, double-click "tasklistdb. MDF", right-click the tables node, and select the "new table" menu item. Open the data table designer and create the following table:
Id int is not empty
Task nvarchar (300) is not empty
Iscompleted bit is not empty
Entrydate datetime is not empty
The first column ID has two attribute settings. First, you must set the ID column as the primary key and then set the ID column as identity for auto-growth ..
Figure 4
Finally, save the table. Name the table tasks.
7. Create a model layer
The MVC model contains most applications and database access logic.Generally, the main classes of MVC applications are placed in the models folder.Put all the code outside the view layer and control layer in the models folder.(CHE Yanlu)
Here we will use LINQ to SQL to interact with the database. I personally like LINQ to SQL. It is not necessary to use LINQ to SQL to write ASP. NET MVC programs. As long as you like, you can use other technologies such as nhib.pdf or other entity frameworks to interact with databases.
Before using LINQ to SQL, you must first create a LINQ to SQL class in the models folder. Right-click the models folder, select "add"-"Add new item", select the "LINQ to SQL classes" template item, and specify the LINQ to SQL class as tasklist dbml. Click Add. The or design page is displayed.
We need to create a LINQ to SQL entity class to present our task table. From the solution file manager, drag the task management table to the or designer, and create an instance class named "LINQ to SQL" for the task. Click Save.
Figure 5
8. Add database logic to the Control Method
Now we have a database. Now we can modify our Controller method so that we can retrieve and store the database. The homecontroller code is as follows.
Listing 4-homecontroller. VB
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;
Using system. Web. MVC;
Using tasklist. models;
Namespace tasklist. Controllers
{
Public class homecontroller: Controller
{
Private tasklistdatacontext DB = new tasklistdatacontext ();
// Display a list of tasks
Public actionresult index ()
{
VaR tasks = from T in dB. Tasks orderby T. entrydate descending select T;
Return view (tasks. tolist ());
}
// Display a form for creating a new task
Public actionresult create ()
{
Return view ();
}
// Add a new task to the database
Public actionresult createnew (string description)
{
// Add the new task to database
Task newtask = new task ();
Newtask. Description = description;
Newtask. iscompleted = false;
Newtask. entrydate = datetime. now;
DB. Tasks. insertonsubmit (newtask );
DB. submitchanges ();
Return redirecttoaction ("Index ");
}
// Mark a task as complete
Public actionresult complete (int id)
{
// Database Logic
VaR tasks = from T in db. tasks where T. ID = ID select T;
Foreach (Task match in tasks)
Match. iscompleted = true;
DB. submitchanges ();
Return redirecttoaction ("Index ");
}
}
}
The homecontroller class has a private member variable dB, which is an instance of the tasklistdatacontext class. The homecontroller class uses dB variables to operate tasklistdb databases.
In index () operation and braking, all records in the task table are retrieved, and the task list is transmitted to the index view.
The createnew () method inserts a new task in the task table. The createnew () method has a string-type parameter description, which receives the description text box in the Form for creating a new task. The ASP. net mvc Framework automatically transmits form fields as parameters to the Controller. (CHE Yanlu)
Finally, the complete () method modifies the value of the iscomplete column in the task table. When we mark that a task has ended, the ID code of the task will be sent to the complete action to modify the database.
9. complete code at the index view layer
We also need to do the last thing to end our tasklist application. We need to modify the index view to display the list of all tasks and allow us to mark the task as an end state. The Code is as follows:
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. tow.datestring () %> -- <% = task. Description %>
</Del>
<%} Else {%>
<A href = "/home/complete/ <% = Task. Id. tostring () %> "> Complete </a>
<% = Task. entrydate. to1_datestring () %> -- <% = Task. Description %>
<% }%>
</LI>
<% }%>
</Ul>
<Br/>
<Br/>
<A href = "/home/create"> Add new task </a>
</Div>
</Body>
</Html>
The index view contains the foreach iteration of C # to traverse all task lists. The task list isViewdata. ModelAttribute obtained .Generally, viewdata is used to transmit data from the action on the control layer to the view layer. .
In a loop, we use a condition to determine whether each task has ended. If the task is finished, the task is displayed as a strikethrough (<del> </del> is a strikethrough function ). If the task has no results, the task is displayed as a hyperlink.
<A href = "/home/complete/<% = task. Id. tostring () %>"> complete </a>
Note that the URL here contains the task id. The task id is passed to the complete () action of the homecontroller class as a parameter. Therefore, when we click the corresponding complete hyperlink, the corresponding database records will be correctly updated.
Finally, the index view displays the following interface:
Figure 6
10. Summary:
This article aims to give us a general understanding of ASP. net mvc applications, from which we can see that ASP. Net MVC web application development is very similar to ASP or ASP. NET.
Here we only use the most basic functions of ASP. net mvc framework. In the subsequent articles, we will conduct in-depth research on various topics (such as controllers, controller actions, views, View data, and HTML helper.