[Original address] ASP. net mvc Framework (Part 4): Handling Form Edit and Post Scenarios
[Original article publication date] Sunday, December 09,200 7 AM
Over the past few weeks, I have been writing a series of posts about the newly developed ASP. NET MVC framework. The ASP. net mvc Framework is an optional method that you can use to structure your ASP. NET web applications, so that they have a clear separation of concerns, so that you can easily test the code and support TDD processes.
The first article in this series creates a simple list of E-commerce Products/browsing websites. It discusses the high-level concepts behind MVC and demonstrates how to create a new ASP. net mvc project from scratch to implement and test the e-commerce product list function. The second part of the series is about ASP. the URL path selection (routing) architecture of the net mvc framework is discussed in depth, its working principle and how you can use it to process more advanced URL path selection scenarios. The third article discusses how the Controller interacts with the view. In particular, it discusses how you can pass View data from the Controller to the view to display the reply Methods returned to the client.
In today's post, I will discuss various methods that you can use the MVC Framework to process form input and submission scenarios, and some HTML auxiliary methods that you can use to simplify data editing scenarios. Click here to download the source code of the complete application built to explain these concepts.
Form input and submission scenarios
To demonstrate some basic principles for processing form input and submission scenarios in the ASP. net mvc framework, we will build a simple product list, product generation, and product editing scenarios. It has three core user experiences:
List of Products by category
Navigate/Products/Category/[CategoryID]You can see the list of all products in a specific product category in this URL:
Add new product
You can click the "Add new product" link above to add a new product to the store. Click to go/Products/NewURL. Here, the system prompts the user to enter the details of the new product to be added:
After you click Save, the product will be added to the database, and then you will go back to the product list page.
Edit Product
On the product list page, you can click "Edit" next to each product. This will go/Products/Edit/[ProductID]URL. Here, you can change the details of the product and click Save to update the database:
Our data model
We will use the SQL Server Northwind sample database to store our data. Then we will use. NET 3.5 built-in LINQ to SQL object (ORM) to model Product, Category, and Supplier objects. These objects represent record rows in our database data tables.
In ASP. in the. net mvc project, right-click the/Models subdirectory and select "Add new item"-> "LINQ to SQL class" to bring up the LINQ to SQL ORM designer to model our data objects:
Then we will create a partial class in the project and add some auxiliary methods to it. We define these helper methods for two reasons: 1) Avoid Embedding our LINQ query directly in our Controller class, 2) it will allow us to change our controller more easily in the future to use dependency injection (dependency injection ).
The auxiliary NorthwindDataContext method we will add is as follows:
For more information about LINQ and LINQ to SQL, refer to the my LINQ to SQL series here.
Build our ProductsController Controller
We will use a single controller class to implement the browsing experience of these three core users. We will call this controller class "ProductsController" (right-click the Controllers subdirectory, select "Add new item"-> "MVC controller" to create this class:
Our ProductsController class will be processed by implementing action methods such as "Category", "New", and "Edit"/Products/Category/3,/Products/New, And/Products/Edit/5Such URL:
To learn how these URLs direct to the action method of the ProductsController class, read part 1 and part 2 of my ASP. net mvc series. In this example, we will use the default/[Controller]/[Action]/[Id]Path ing rules, which means thatNot RequiredIf you configure something, the path orientation will automatically happen.
The Action method of our controller uses three view webpages to display the output. "List. aspx "," New. aspx ", and" Edit. aspx "Web pages will reside in the \ Views \ Products subdirectory. These web pages will be based on the Site in the \ Views \ Shared directory. master page.
List of products listed by class
The first part of the website we want to implement will be the product list URL (/Products/Category/[CategoryId]):
We will use the "Category" action Method on our ProductsController class to implement this function. We will use the LINQ to SQL DataContext class, And the GetCategoryById auxiliary method we added to it to obtain a Category object, which represents a URL (for example, /Products/Category/3) specifies a specific Category. Then, we pass the Category object to the "List" view to generate a reply:
When implementing our List view, we first update the background code of our webpage, inherited from ViewPage <Category>, in this way, the ViewData attribute of the page will be the type of the Category object passed from our controller (the third part will be discussed in detail ):
Then we will implement List. aspx as follows:
The preceding view displays the category name at the top of the page, and the project list of all products in the category is displayed.
There is an "Edit" link next to each product in the project list. We use the Html discussed in the second part. the ActionLink auxiliary method to display these HTML hyperlinks (for example, <a href = "/Products/Edit/4"> Edit </a>, after the "Edit" link is clicked, the user is directed to the "Edit" action method. Then we will use Html. the ActionLink auxiliary method generates a <a href = "/Products/New"> Add New Product </a> link at the bottom of the page. After the link is clicked, the user will be directed to the "New" action method.
When we access the/Products/Category/1 URL and view the source code in the browser, you will notice that our ASP. net mvc application outputs a very clean HTML and URL identifier:
Add new products (part 1-background knowledge)
Now, let's implement the "Add new product" form submission function for the website. Finally, we want users to access/Products/NewThe URL is shown as follows:
In the ASP. net mvc Framework, the form input and editing scenarios are generally handled by displaying two Action methods in the Controller class. The first Controller Action method is used to send the HTML containing the initial form to be displayed. The second Controller Action method is responsible for processing any form submissions sent back from the browser.
For example, on the "add product" screen above, we will select two different actions on ProductsController to implement: "New" and "Create "./Products/NewThe URL displays a blank form with an HTML text box and a drop-down box control, allowing users to enter details of the new product. Then, the HTML <form> element on the webpage sets its action attribute/Products/CreateURL. This means that when you click the form submission button, the form input will be sent to the "Create" action method to process and update the database.
Add a new product (Part 2-method 1)
The following is an initial implementation of ProductsController.
Note that in the process of product generation, we have two action methods,-"New" and "Create ". The "New" action method simply displays a blank form to the user. The "Create" action method processes the values submitted from the form, generates a new product based on these values in the database, and then redirects the customer to the category list page of the product.
The HTML form sent to the client is implemented in the "New. aspx" View called by the "New" action method. An initial implementation of this view (each input uses a text box) Looks like the following:
Note that the standard HTML <form> element is used on the webpage, instead of form runat = server. The "action" attribute of the form is set to the "Create" action Method on ProductsController. When the <input type = "submit"> element at the bottom of the page is clicked, The commit occurs. After that, ASP. net mvc Framework automatically maps ProductName, CategoryID, SupplierID, and UnitPrice values to method parameters and passes them to the "Create" action Method on ProductsController:
At this point, when we run the website, we have the most basic product input function:
Add a new product (Part 3-use the HTML-assisted method to implement the drop-down box)
The product input screen we created in the previous section is feasible, but not very friendly. Specifically, it requires the user to know the original CategoryID and SupplierID members of the product being entered. We need to solve this problem by displaying the HTML drop-down box containing the readable name.
Step 1: Modify ProductsController to send two sets to the view, one containing the existing category list and the other containing the product supplier list. We will generate a strongly typed ProductsNewViewData class that encapsulates these lists, and then pass it to the view for this purpose (you can learn more in Part 3 ):
Then we will update the "New" action Method to fill these sets, and then pass them as ViewData to the "New" View:
Then, in our view, we can use these sets to generate an HTML <select> drop-down box.
Auxiliary methods for ASP. NET MVC HTML
One method we can use to generate a drop-down box is to manually generate a for-loop containing the if/else statement in HTML. This gives us full control over HTML, but HTML will be messy.
The cleaner method you can use is to use the "Html" Auxiliary attribute on the ViewPage base class. This is a convenient object and shows a set of HTML auxiliary interface methods for automatic HTML interface generation. For example, before this post, we use the Html. ActionLink helper method to generate the <a href = ""> element:
HtmlHelper object (and the AjaxHelper object we will discuss later) is specially designed to use the "Extension Method" (a new language feature of VB and C # In VS 2008). This means that anyone can generate their own custom auxiliary methods for these objects and share these methods for your use.
In the future preview of the ASP. net mvc framework, we will provide dozens of built-in HTML and AJAX auxiliary methods. In the first preview, only the "ActionLink" method is built in System. Web. Extensions (the Assembly that currently implements the core ASP. net mvc Framework. However, we will also have a separate "MVCToolkit" Download. You can add it to your project to get dozens of helper methods you can use in the first preview.
To install the MVCToolkit HTML helper method, you just need to add the MVCToolkit. dll assembly as a reference for your project:
Recompile your project, and next time you type <% = Html. %>, you will see a lot of additional interface helper methods you can use:
To generate an HTML <select> drop-down box, we can use the Html. Select () method. Each method has an overloaded version, and the view has the complete intelliisense:
We can update our "New" view, use the following code, use the Html. Select option to display the CategoryID/SupplierID attribute as the value, and CategoryName/SupplierName as the drop-down box of the display text:
This will generate an appropriate <select> HTML identifier during runtime:
On the/Products/New screen, you can easily select product categories and suppliers:
Note: because we are still submitting CategoryID and SupplierID values to the server, we do not need to update the Create Action Method of ProductsController to support this new drop-down box interface. This method still works.
Add a new product (Part 4-use the UpdateFrom method to clear the Create code)
The "Create" Action Method of ProductsController is used to process the form submission for the "add product" scenario. Currently, it uses the action method parameter to process the following form parameters:
This method is feasible, but for forms involving a large number of values, the signature of the Action method will become a bit difficult to read. In addition, the Code for setting all incoming parameter values to the new Product object is long and monotonous.
If you reference the MVCToolkit assembly, you can use a useful extension method implemented in the System. Web. Mvc. BindingHelpers namespace to clean up the code. This extension method is called "UpdateFrom" and can be used on any. NET object. It accepts a dictionary as a parameter, and then it automatically assigns an attribute value to itself for any public attribute key that matches the object.
For example, we can rewrite the above Create action method to use the UpdateFrom method, as shown in the following code:
Note: If you want to be more specific for security reasons and only allow certain attributes to be updated, you can also pass in a string array with UpdateFrom method that can update the attribute name:
Implement the product editing function (part 1-background knowledge)
Now let's implement the website "Edit product" function. We finally want users to access/Products/Edit/[ProductID]The following screen is displayed at URL:
Like in the preceding example of adding a new product form, two ProductsController Action methods are used for form editing interaction, the two methods are called "Edit" and "Update ":
"Edit" will display the product form, and "Update" will be used to process the form submission action.
Implement the product editing function (Part 2-Edit Action)
We will enable the Edit function of our application by implementing the Edit action Method of ProductController. When we create a product list webpage at the beginning of this post, we create this webpage. The Edit action accepts an id parameter as part of the URL (for example, /Products/Edit/5 ):
We want the Edit Action method to obtain appropriate product objects from the database, as well as existing product suppliers and classification sets (in this way, we can implement the corresponding drop-down boxes in our editing view ). We will use the following ProductsEditViewData object to define a strong view object to represent all the data:
Then, we can implement our Edit action Method to fill in this viewdata object and display it in the "Edit" View:
Implement the product editing function (Part 3-Edit view)
We can use the following methods to implement the Edit. aspx view webpage:
Note how we can use the Html. TextBox and Html. Select auxiliary methods in the preceding example at the same time. Both methods are derived from the extension methods in the MVCToolkit. dll assembly.
Note that the Html. Select helper method has an overloaded version that allows you to specify the selected value in the drop-down box. In the following code snippet, I will automatically select a Category according to the current CategoryID value of the product to be edited in the Category drop-down box:
Finally, note how to use the Url. Action () helper method to set the action attribute of the <form> element:
Url. Action and Html. ActionLink both use the path selection engine of the ASP. net mvc Framework to generate a URL (see section 2 for details about the URL generation principles ). This means that if we change the path selection rules for the editing function of our websiteNoYou need to modify any code in the Controller or view. For example, we can remap our URLs to replace/Products/Edit/1, but use a more RESTful URL like/Products/1/Edit, the Controller and view code above does not need to be modified, but will still work.
Implement the product editing function (Part 4-Update Action)
The last step is to implement the "Update" action Method on the ProductController class:
Like the above "Create" action method, we will use the "UpdateFrom" Extension Method to automatically fill in our product objects from the request. However, note that the filling is not an empty object. We use a mode to obtain the old value from the database, apply the changes made to the user, and update the changes to the database.
After compilation, we redirect to the product list page and automatically set/Products/Category/[CategoryID] to match the saved status of the product we are working on.
Conclusion
I hope this post provides. in the. net mvc framework, some details about how to deal with form input and submission scenarios are also provided with some background about how you can process and structure common data input and editing scenarios.
Click here to download a. ZIP file containing the complete application source code we have built above.
In future posts, I will discuss how to handle data verification and error recovery in form input and editing scenarios. I will discuss some built-in data and security brackets (scaffolding) that facilitate rapid application development ). I will discuss how you can use ASP. NET AJAX in the MVC framework to enable AJAX editing. I will also discuss in depth how to unit test controllers and how to add dependency injection to controllers.