Scott's Asp.net MVC Framework series Article 4: Processing Form data (2)

Source: Internet
Author: User
Tags actionlink

Several weeks ago I published a series of articles about the ASP. NET MVC framework that we are studying. ASP. the net MVC Framework provides you with a new way to develop Web applications, which can make the applications more hierarchical and clear, in addition, it is more conducive to code unit testing and tdd (test-driven development) development.

The first article in these columns creates a simple e-commerce product list/browsing site. He involved the high-level concepts behind MVC and demonstrated the process from design to implementation of an ASP. net mvc project and the test of the product list function. The second article in this series introduces the URL ing mechanism of ASP. net mvc Framework in depth, and discusses its working principle and processing of more complex URL ing. The third article discusses the interaction between the control class and the view, and specifically introduces how to transmit data from the control class to the view to generate client rendering.

This article will discuss how to use the ASP. net mvc Framework to process form input submission operations. It will also discuss some HTML extension methods that can be used to simplify data editing. Click here to download the complete application code to help you understand these concepts.

Form input and submission operations

To demonstrate how to use the ASP. net mvc Framework to edit and submit forms, we will create a simple product list/product creation and product editing application. He will provide users with three core functions:

List products by directory

You can access the product list in a directory through the/products/category/[categoryid] address:

Add new product

You can click the "Add new produt" link to add a new product to the store. This link links the user to the/products/new address, allowing the user to enter the details of the added product.

Click "save" to add the product to the database. The product list page is displayed.

Edit Product

On the product list page, you can click "edit" next to each product to link to the/products/edit/[productid] address, allowing you to modify the details of the corresponding product, click Save to save the new information to the database.

Data Model

We use the SQL server's northwind sample database to store our data. We will apply the built-in LINQ to SQL ing mechanism to products, directories, and supplier suppliers and their database tables. net3.0.

Right-click the/model subdirectory in the ASP. net mvc project, select "Add new project"-> "LINQ to SQL class", open the LINQ to SQL ORM designer, and model the data object:

Then we will create the northwinddatacontext distribution class in the project and add some auxiliary methods. We define these auxiliary methods for two considerations: 1) Avoid embedding a LINQ query statement directly into the Controller Class 2) prepare for future dependency injection on the Controller class.

The auxiliary method of northwinddatacontext to be added is as follows:

Click here to view the articles in the LINQ to SQL series to learn more about LINQ to SQL.

CreateProductscontrollerClass

We will use the productscontroller class to implement the three core functions mentioned above (by right-clicking the controllers sub-folder and selecting "Add new project"-> "MVC control class" to create ):

The productscontroller class will implement category, and the new and edit methods will process urlqingqiu, which is similar to/products/category/3,/products/New and/products/edit/5.

Read part 1 and part 2 in this series to learn more about URL-to-control method ing.

The control class method generates output content through three views pages. "List. aspx "New. aspx "and" edit. aspx "Page, they use the site under the \ views \ shared directory. master board page.

Display the product list based on the directory

First, implement the product list URL request/products/category/[categoryid]:

We use the "category" method in productscontroller to implement this function, and use the getcategorybyid auxiliary method in the LINQ to SQL datacontext class to obtain the information in the URL (for example,/products/category/3) and then pass the directory object to the "list" view and display the output:

To implement the list view, first modify the background code file of the page to inherit from the viewpage <Category> base class, define the viewdata property type received from the controller control class on the page as category (discussed in detail in Part 3 ):

The implementation of list. aspx is as follows:

The preceding view displays the directory name at the top of the page and the product list of the directory.

The "edit" link is next to each product item in the list. We will use the HTML. actionlink () is used to generate html links (for example, <a href = "/products/edit/4"> edit </a>). Click the link to edit the link. At the same time, we need to use this method to generate the <a href = "/products/New"> Add new product </a> link at the bottom of the page, and click this link to perform the "new" operation.

When we open the/products/category/1 Address and view the source code in the browser, you will find that our ASP. net mvc application has migrated the neat HTML and URL tags:

Add new product functions(1-Background)

Next we will implement the "Add new product" function. We finally want the user to see the following interface when accessing the/products/new address:

In the ASP. net mvc Framework, form input and editing are usually implemented by two methods in the Controller class. The first method is used to generate and send HTML code containing the form, and the other is used to process the submitted information sent back by the browser.

For example, for the above "add product" form, we can use two methods in productscontroller to implement: "New" and "CREATE ". The/products/new request is used to display an empty form that contains the HTML text box and the drop-down menu control used to enter product information. The action attribute of the HTML <form> element on this page is set to/products/create, which means that when you click the submit form button, the input information of the form will be sent to the "Create" method for processing and updating the database.

Add new product implementation (2-Method 1)

The following describes how to implement the productscontroller class:

Note that the above Code uses two methods "new" and "CREATE" during product creation ". The "New" method presents a blank form to the user. The "CREATE" method processes the data submitted in the form, creates a new product in the database, and locates the browser on the product list page.

"News. aspx" defines the HTML form sent to the client and is called by the new method. Its implementation (all implemented using textbox) is as follows:

Note how we use the standard HTML <form> element (not form runat = server ). The action attribute of the form submits the data to the create method of the productcontroller class for processing. When the <input type = "Submit"> element at the bottom is clicked, data is submitted. asp. net MVC Framework will automatically pass in the values of productname, categoryid, supplierid, and unitprice as parameters of the create method.

Run the site that already has the basic product features:

Add new product implementation (3-UseHtmlAuxiliary)

We have completed the product item page, but the interface is not friendly enough. Because you must know the original categoryid and supplierid when adding a product. We want to display the HTML drop-down list to display a directory name to solve this problem.

Our first step is to modify productscontroller so that it can pass two sets of data to the view, one containing a list of available directories, and the other can be a list of available suppliers. We create a strongly typed productsnewviewdata class to encapsulate the data and pass it to the view (Part 3 introduces this part in detail ):

We need to update the "new" method to process these set data and pass it to the "new" view as viewdata:

In our view, we can use these set data to generate an HTML drop-down list.

ASP. net mvc htmlAuxiliary Methods

We can use <%> embedded for loop statements containing IF/else in HTML to generate a drop-down list. In this way, we can have full control over HTML, but this will make HTML code messy.

You can also select the "html" Secondary attribute in the base viewpage class. This object is used to automatically generate html ui by using html ui auxiliary methods. For example, the preceding html. actionlink method is used to generate <a href = ''> elements:

Htmlhelper object (including the ajaxhelper object to be mentioned later) is designed to be easy to use the extension method extension methods (new language features of VB and C # In vs2008) this allows anyone to create and use custom auxiliary methods in this object.

In the future ASP. net mvc framework, we will provide more built-in HTML and Ajax auxiliary methods. In the first preview version, the "actionlink" method is only embedded in the system. Web. Extensions (the Assembly currently implemented by the ASP. net mvc Framework. We also provide an independent mvctoolkit for downloading. You can use it as more auxiliary methods in the project.

To use the mvctoolkit HTML helper method, you only need to add the mvctoolkit. dll assembly to your project reference:

Re-compile the project. The next time you use <% = html. %>, you will see more UI auxiliary methods:

We can use the HTML. Select () method to construct the HTML <SELECT> drop-down list. Each method contains multiple overloaded versions and supports intelligent sensing:

You can use the HTML. select option in the "new" view to display the drop-down list, use categoryid/supplierid as the value attribute, and use categoryname/suppliername as the display text attribute. The Code is as follows:

The corresponding <SELECT> HTML Tag will be generated at runtime:

This allows you to easily select the product catalog and supplier information:

Note: Because we still submit categoryid and supplierid values, we do not need to update the create method of productscontroller on the new drop-down list interface.

Add new product implementation (4-UseUpdateformMethod to end the creation process)

The create method of the productscontroller class is used to process the data submitted by adding a product form. Currently, this method uses the form data as a parameter to pass in the method:

Although this method requires a large number of parameters to be specified in the method signature, this method can still work normally. The code above passes all input form values to the products object, the code is still a little complicated.

If you reference the mvctoolkit assembly, you can use an extension method implemented in the system. Web. MVC. bindinghelpers namespace to simplify the code. This method is "updateform" and can be referenced in all. Net objects. It contains a dictionary value as a parameter and automatically copies the attribute with the same name as the key name in the object.

For example, we can use the updateform method to override the create method:

 

Note: If you want to be more rigorous for security reasons and only assign values to certain attributes, You can input a string array containing the attribute names to be updated to the updateform method:

Edit the product function implementation (1-Background)

Now you can edit the product of the site. We want the end user to see the access/products/edit/[productid] address to see the following interface:

Similar to the form of the product added above, we make this form interact with the "edit" and "Update" methods in productscontroller:

"Edit" displays the product form, and "Update" is used to process submitted data.

Edit the product function implementation (2-EditMethod)

We implement the Edit Method in productscontroller to edit the product function of the application. After the product features are created and compiled, the Edit () method requires that part of the URL be used as an ID parameter (for example,/products/edit/5 ):

We hope that the edit method can obtain the specified product objects and available suppliers and product sets from the database (used to display the drop-down list in the editing view ), we can define a strongly typed productseditviewdata view Data Object representative.

We can implement the Edit Method to process viewdata objects and render them through the "edit" View:

Edit the product function implementation (2-Edit view)

We can implement the edit. aspx view page in the following way:

Note how we use the HTML. textbox and HTML. Select helper methods in the preceding example. Both of these helper methods are from the mvctoolkit. dll assembly.

Note: HTML. the Select auxiliary method provides an overload method that allows you to specify the selected value in the drop-down menu. In the following code segment, the selected items in the product catalog drop-down list are automatically set to the selected values of the current product catalog:

Finally, you must use the URL. Action () method to set the action attribute of the <form> element:

URL. action and HTML. the action method uses ASP. net MVC Framework ing engine generates a URL (part 2 describes this part in detail ). if we modify the ing rules of a site, we do not need to modify any code in the control class or view. For example, we can use a restful path, such as replacing/products/1/edit with/products/edit/1. The control class and view can still work normally without any modifications.

Edit the product function implementation (3-UpdateMethod)

The last step is to implement the update method in productscontroller:

In the previous create method, we used the updateform Extension Method to automatically obtain the product object from the request. here we need to first obtain the original object data from the database, then, apply the modifications made by the user to the object and save the changes to the database.

After the modification is successful, the page is returned to the product list and the corresponding list of modified applications for the product is automatically displayed.

Summary

It is hoped that this article will clearly describe the processing of form input and adjustment in ASP. net mvc Framework, and provide examples of using this method to edit and process common data items.

Click here to download the code file containing the application.

The following article describes how to perform data verification and error capture on the form input and edit applications. I will introduce the built-in data and security support for quick development, and discuss how to use ASP in the MVC framework. netajax implements Ajax, and discusses in depth the unit test and dependencies injection operations on the controller.

Hope to help you,

Scott

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.