ASP.NET MVC Preview 5 and Form Posting Scenarios
page 2 of 9
by Scott Guthrie
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 40278/ 82

Basic Form Post with a Web MVC Pattern

Let's look at a simple form post scenario - adding a new product to a products database:

The page above is returned when a user navigates to the "/Products/Create" URL in our application.  The HTML form markup for this page looks like below:

The markup above is standard HTML.  We have two <input type="text"/> textboxes within a <form> element.  We then have an HTML submit button at the bottom of the form.  When pressed it will cause the form it is nested within to post the form inputs to the server.  The form will post the contents to the URL indicated by its "action" attribute - in this case "/Products/Save".

Using the previous "Preview 4" release of ASP.NET we might have implemented the above scenario using a ProductsController class like below that implements two action methods - "Create" and "Save":

The "Create" action method above is responsible for returning an html view that displays our initial empty form.  The "Save" action method then handles the scenario when the form is posted back to the server.  The ASP.NET MVC framework automatically maps the "ProductName" and "UnitPrice" form post values to the method parameters on the Save method with the same names.  The Save action then uses LINQ to SQL to create a new Product object, assigns its ProductName and UnitPrice values with the values posted by the end-user, and then attempts to save the new product in the database.  If the product is successfully saved, the user is redirected to a "/ProductsAdded" URL that will display a success message.  If there is an error we redisplay our "Create" html view again so that the user can fix the issue and retry.

We could then implement a "Create" HTML view template like below that would work with the above ProductsController to generate the appropriate HTML.  Note below that we are using the Html.TextBox helper methods to generate the <input type="text"/> elements for us (and automatically populate their value from the appropriate property in our Product model object that we passed to the view):


View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-02-27 10:56:57 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search