ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

The last few weeks I have been working on a series of blog posts that cover the new ASP.NET MVC Framework we are working on.  The ASP.NET MVC Framework is an optional approach you can use to structure your ASP.NET web applications to have a clear separation of concerns, and make it easier to unit test your code and support a TDD workflow.

The first post in this series built a simple e-commerce product listing/browsing site.  It covered the high-level concepts behind MVC, and demonstrated how to create a new ASP.NET MVC project from scratch to implement and test this e-commerce product listing functionality.  The second post drilled deep into the URL routing architecture of the ASP.NET MVC framework, and discussed both how it worked as well as how you can handle more advanced URL routing scenarios with it.  The third post discussed how Controllers interact with Views, and specifically covered ways you can pass view data from a Controller to a View in order to render a response back to a client.

In today's blog post I'm going to discuss approaches you can use to handle form input and post scenarios using the MVC framework, as well as talk about some of the HTML Helper extension methods you can use with it to make data editing scenarios easier.  Click here to download the source code for the completed application we are going to build below to explain these concepts.

Form Input and Post Scenario

To help illustrate some of the basics of how to handle form input and posting scenarios with the ASP.NET MVC Framework, we are going to build a simple product listing, product creation, and product editing scenario.  It will have three core end-user experiences:

Product Listing By Category

Users will be able to see a listing of all products within a particular product category by navigating to the /Products/Category/[CategoryID] URL:

Add New Product

Users will be able to add a new product to the store by clicking the "Add New Product" link above.  This takes them to the /Products/New URL - where they will be prompted to enter details about a new product to add:

When they hit save, the product will be added to the database, and they will be redirected back to the product listing page.

Edit Product

On the product listing page users can click the "Edit" link next to each product.  This takes them to the /Products/Edit/[ProductID] URL - where they can change the product details and hit the Save button in order to update them in the database:

Our Data Model

We are going to use the SQL Server Northwind Sample Database to store our data.  We'll then use the LINQ to SQL object relational mapper (ORM) built-into .NET 3.5 to model the Product, Category, and Supplier objects that represent rows in our database tables. 

We'll begin by right-clicking on our /Models sub-folder in our ASP.NET MVC project, and select "Add New Item" -> "LINQ to SQL Classes" to bring up the LINQ to SQL ORM designer and model our data objects:

We'll then create a partial NorthwindDataContext class in our project and add some helper methods to it.  We are defining these helper methods for two reasons: 1) it avoids us embedding our LINQ queries directly in our Controller classes, and 2) it will enable us to more easily adapt our Controller to use dependency injection in the future.

The NorthwindDataContext helper methods we'll add look like below:

To learn more about LINQ and LINQ to SQL, please check out my LINQ to SQL series here.

Building Our ProductsController

We are going to implement all three of our core end-user browsing experiences using a single controller class - which we'll call "ProductsController" (right click on the "Controllers" sub folder and select "Add New Item" -> "MVC Controller" in order to create it:

Our ProductsController class will handle URLs like /Products/Category/3, /Products/New, and /Products/Edit/5 by implementing "Category", "New", and "Edit" actions:

Read Part 1 and Part 2 of my ASP.NET MVC Series to learn more about how these URLs are routed to the action methods on the ProductsController class.  For this sample we are going to use the default /[Controller]/[Action]/[Id] route mapping rule - which means we do not need to configure anything in order for the routing to happen.

Our Controller actions will be using three View pages in order to render output.  The "List.aspx", "New.aspx", and "Edit.aspx" pages will live under the \Views\Products sub-folder, and be based on the Site.Master master page under \Views\Shared.

Implementing Product Listing By Category

The first part of the site that we'll implement will be the Product Listing URL (/Products/Category/[CategoryId]):

We'll implement this functionality using the "Category" action on our ProductsController class.  We'll use our LINQ to SQL DataContext class, and the GetCategoryById helper method we added to it, to retrieve a Category object that represents the particular category indicated by the URL (for example: /Products/Category/3).  We'll then pass the Category object to the "List" view to render a response from it:

When implementing our List view we'll first update our page's code-behind to derive from ViewPage<Category> so that our page's ViewData property will be typed to the Category object that was passed by our Controller (Part 3 discusses this more):

We'll then implement our List.aspx like below:

The above view renders the Category name at the top of the page, and then renders a bulleted list of the Products within the category. 

Next to each product in the bulleted list is an "Edit" link.  We are using the Html.ActionLink helper method that I discussed in Part 2 to render a HTML hyperlink (for example: <a href="/Products/Edit/4">Edit</a>) that when pressed will navigate the user to the "Edit" action.  We are also then using the Html.ActionLink helper method again at the bottom of the page to render a <a href="/Products/New">Add New Product</a> link that when pressed will navigate the user to the "New" action.

When we visit the /Products/Category/1 URL and do a view-source in the browser, you'll notice that our ASP.NET MVC application has emitted very clean HTML and URL markup:

Implementing Add New Product (Part 1 - Background)

Let's now implement the "Add New Product" form post functionality of our site.  We'll ultimately want users to see a screen like below when they visit the /Products/New URL:

Form input and editing scenarios are typically handled in the ASP.NET MVC Framework by exposing two Action methods on a Controller class.  The first Controller Action method is responsible for sending down the HTML containing the initial form to display.  The second Controller action method is then responsible for handling any form submissions sent back from the browser.

For example, for our "Add Product" screen above we could choose to implement it across two different ProductsController actions: one called "New" and one called "Create".  The /Products/New URL would be responsible for displaying an empty form with HTML textboxes and drop-down list controls to enter new product details.  The HTML <form> element on this page would then have its "action" attribute set to the /Products/Create URLThis means that when the user presses a form submit button on it, the form inputs will be sent to the "Create" action to process and update the database with.

Implementing Add New Product (Part 2 - First Approach)

Below is an initial implementation that we could use for our ProductsController. 

Notice above that we now have two action methods involved in the product creation process - "New" and "Create".  The "New" action method simply displays a blank form to the user.  The "Create" action method is what processes the posted values from the form, creates a new Product in the database based on them, and then redirects the client to the category listing page for 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 (using textboxes for everything) would look like below:

Note above how we are using a standard HTML <form> element on the page (not a form runat=server).  The form's "action" attribute is set to post to our "Create" action method on ProductsController.  The post will happen when the <input type="submit"> element at the bottom is pressed.  When this happens, the ASP.NET MVC Framework will automatically handle mapping the ProductName, CategoryID, SupplierID and UnitPrice values as method parameters to the "Create" action method on ProductsController:

And now when we run the site we have basic product entry functionality working:

Implementing Add New Product (Part 3 - Using HTML Helpers for Drop Down Lists)

The product entry screen we created in the previous section works, but isn't very user friendly.  Specifically, it requires that the end user know the raw CategoryID and SupplierID numbers for the Product being entered.  We need to fix this by instead displaying an HTML dropdownlist that displays the human readable names.

Our first step will be to modify our ProductsController to pass to the View two collections - one containing a list of available categories, the other a list of available suppliers.  We'll do this by creating a strongly typed ProductsNewViewData class that encapsulates these, and which we'll then pass to the View (you can learn about this in Part 3):

We'll then update our "New" action method to populate these collections and pass them as the ViewData for the "New" view:

Within our view we can then use these collections to generate HTML <select> dropdowns. 

ASP.NET MVC HTML Helpers

One approach we could use to generate our dropdowns would be to manually create our own <% %> for-loop containing if/else statements within the HTML.  This would give us total control over the HTML - but would make the HTML messy.

A much cleaner approach that you can alternatively use is to take advantage of the "Html" helper property on the ViewPage base class.  This is a convenient object that exposes a set of HTML Helper UI methods that automate HTML UI generation.  For example, earlier in this post we used the Html.ActionLink helper method to generate <a href=""> elements:

The HtmlHelper object (as well as the AjaxHelper object - which we'll talk about in a later tutorial) have been specifically designed to be easily extended using "Extension Methods" - which is a new language feature of VB and C# in the VS 2008 release.  What this means is that anyone can create their own custom helper methods for these objects and share them for you to use. 

We'll have dozens of built-in HTML and AJAX helper methods in future previews of the ASP.NET MVC Framework.  In the first preview release only the "ActionLink" method is built-into System.Web.Extensions (the assembly where the core ASP.NET MVC framework is currently implemented).  We do, though, also have a separate "MVCToolkit" download that you can add to your project to obtain dozens more helper methods that you can use with the first preview release. 

To install the MVCToolkit HTML Helper methods, simply add the MVCToolkit.dll assembly to your project references:

Re-build your project.  And then the next time you type <%= Html. %> you'll see many, many more additional UI helpers that you can use:

To build our HTML <select> dropdowns we could use the Html.Select() method.  Each method comes with overloaded method versions - all with full intellisense inside our views:

We could update our "New" view to use the Html.Select options to display dropdownlists that use the CategoryID/SupplierID properties as the values and CategoryName/SupplierName as the display text using the code below:

This will generate the appropriate <select> HTML markup for us at runtime:

And give end-users an easier way to pick the Product Category and Supplier on our /Products/New screen:

Note: because we are still posting a CategoryID and SupplierID value to the server, we do not need to update our ProductsController Create Action at all to support this new drop-downlist UI - it will just work.

Implementing Add New Product (Part 4 - Cleaning Up Create with the UpdateFrom Method)

Our ProductsController's "Create" Action method is responsible for handling the form posting of our "Add Product" scenario.   It currently handles incoming form parameters as arguments to the action method:

This approach works fine - although for forms involving large amounts of values the method signatures on Actions can start to become a little hard to read.  The code above that sets all of the incoming parameter values to the new Product object is also a little long and monotonous.

If you reference the MVCToolkit assembly, you can optionally take advantage of a useful Extension Method implemented within the System.Web.Mvc.BindingHelpers namespace that can help clean this up a little.  It is called "UpdateFrom" and can be used on any .NET object.  It takes a dictionary of values as an argument, and it will then automatically perform a property assignment on itself for any key that matches a public property on the object.

For example, we could re-write our Create action method above to use the UpdateFrom method like so:

 

Note: if you want to be more explicit for security reasons and only allow certain properties to be updated, you can also optionally pass a string array of the property names to update to the UpdateFrom method:

Implement Edit Product Functionality (Part 1 - Background)

Let's now implement the "Edit Product" functionality of our site.  We'll ultimately want users to see a screen like below when they visit the /Products/Edit/[ProductID] URL:

Like the "Add New Product" form post example above, we are going to implement this form edit interaction using two ProductsController Actions that we'll call "Edit" and "Update": 

"Edit" will display the product form.  "Update" will be used to handle the form's submit action.

Implement Edit Product Functionality (Part 2 - Edit Action)

We'll begin enabling our application's Edit functionality by implementing the ProductController's Edit action method.  When we created our product listing page at the beginning of this post, we built it so that the Edit action will take an id argument as part of the URL (for example: /Products/Edit/5):

We'll want the Edit action method to retrieve the appropriate Product object from the database, as well as retrieve collections of the available Suppliers and Categories (so that we can implement dropdowns in our edit view).  We'll define a strongly typed view object to represent all of this using the ProductsEditViewData object below:

We can then implement our Edit action method to populate this viewdata object and Render it with an "Edit" view:

Implement Edit Product Functionality (Part 2 - Edit View)

We can implement the "Edit.aspx" view page using the following approach:

Note how we are using both the Html.TextBox and Html.Select helper methods in the sample above.  Both of these are extension methods from the MVCToolkit.dll assembly.

Notice how the Html.Select helper method has an overloaded version that allows you to specify what the selected value is in the dropdownlist.  In the snippet below I'm indicating that I want the Category drop down item to be automatically selected based on the edit product's current CategoryID value:

Lastly - notice how we are using the Url.Action() helper method to set the <form> element's "action" attribute:

Both the Url.Action and Html.ActionLink helper methods use the ASP.NET MVC Framework's Routing Engine to generate URLs (read Part 2 for details on how URL generation works).  What this means is that if we change the routing rules for Edits in our site, we will not need to change any of the code in our Controller or View.  For example, we could re-map our URLs to use a more RESTful URL like /Products/1/Edit instead of /Products/Edit/1, and have the above Controller and View continue to work unmodified. 

Implement Edit Product Functionality (Part 3 - Update Action)

Our last step will be to implement the "Update" action method on our ProductController class: 

Like our previous "Create" action method we'll take advantage of the "UpdateFrom" extension method to automatically populate our product object from the request.  Notice that rather then populate an empty product object though, we are using a pattern where we first retrieve the old values from the database, then apply the changes the user made to them, and then save them in the database. 

Once the edit is made, we redirect back to the Product Listing page - and automatically set the /Products/Category/[CategoryID] to match the saved state of the Product we were working on.

Summary

Hopefully this post has helped provide some more details about how to handle Form Input and Post scenarios with the ASP.NET MVC Framework, as well as provided some context for how you can handle and structure common data entry and edit scenarios with it.

Click here to download a .ZIP file that contains the source code for the completed application we built above.

In future posts I'll cover how to handle validation and error recovery situations with form input and editing scenarios. I'll talk about some of the data and security scaffolding support built-in to enable rapid application creation.  I'll discuss how you can use ASP.NET AJAX to perform AJAX-enabled edits using the MVC framework.  And I'll drill deeper into how you can unit test and add dependency injection to your Controllers.

Hope this helps,

Scott

Published Sunday, December 09, 2007 4:42 AM by ScottGu
Filed under: , ,

Comments

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 7:54 AM by liviu

This is nice. But do you handle subcomponents? subviews? Is view reuse possible inside other view?

This is very important for even for modest sized applications? How would you handle posts correcly inside of subviews ;) ?

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 7:57 AM by panjkov

is this correct link for asp.net extensions preview that will be shipped (today?)

go.microsoft.com/fwlink

(taken from www.hunterstrat.com/.../microsoft-releases-adonet-entity-framework-aspnet-35-extensions-previews)

it is pointing here

www.microsoft.com/.../details.aspx

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 7:59 AM by ScottGu

Hi Liviu,

>>>>>>> This is nice. But do you handle subcomponents? subviews? Is view reuse possible inside other view? This is very important for even for modest sized applications? How would you handle posts correcly inside of subviews ;) ?

The first public MVC preview doesn't have the concept of SubControllers yet (where you can attach them for regions of a larger view).  That is something we have planned for to tackle soon though.  

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 8:00 AM by ScottGu

Hi Panjkov,

>>>>>> is this correct link for asp.net extensions preview that will be shipped (today?) go.microsoft.com/fwlink (taken from www.hunterstrat.com/.../microsoft-releases-adonet-entity-framework-aspnet-35-extensions-previews )

No - that is for the ADO.NET entities bits (which is something different).  Keep an eye on www.asp.net in a few hours - the ASP.NET 3.5 Extensions Preview (which includes MVC) will be posted there shortly.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 8:01 AM by panjkov

i know, but in that post are mentioned asp.net extensions, too

# ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 8:08 AM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 8:09 AM by David Lawton

*applause*

Top work Scott, I have been on the edge of my seat awaiting the MVC framework and can just about see it over the horizon.

1 Question, how will the framework handle file uploads? It just occured to me that in your example its a product your adding/updating and noticed there was no image upload functionality.

Apart from that excellent work, very excited about this.

Dave "The Ninja" Lawton

Hyperion Technologies UK Ltd.

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 8:18 AM by panjkov

it is also announced in ms presspass...

"the ASP.NET 3.5 Extensions preview will be available at go.microsoft.com/fwlink

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 8:29 AM by Chris Hardy

What's the LINQ to SQL support like with using dates? I remember when I was trying to use date/times with LINQ it didn't like it at all and came up with all sorts of errors. It'd be good to essentially timestamp when new products were added or edited and I was wondering if using LINQ/MVC would make this a little easier?

These tutorials are great though and get you up on your feet very quickly!

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 8:51 AM by Vijay Santhanam

I dig the separation of concerns ideology of mvc. I particularly like the routing engine and the flexibility and extensibility of all Engines.

I like the BindingHelpers too - it greatly helps with mundane property setting.

However, liviu raises good questions about Sub-Controllers, Composite Views and AJAX scenarios. How Will the MVC framework address the complex wiring of different parts of a page to different controllers for async updates?? My brain hurts thinking about it, yet I have implement these portal pages all the time cos our customers demand it.

Great work Scott! Can't wait for the binaries

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 8:58 AM by Martin Robins

Excellent post as always; a few questions though ...

1.) Is it fair to read into this that the extensions in the MVCToolkit.dll will eventually be integrated into the main System.Web.Extensions.dll or will they always be in a seperate assembly?

2.) Will the source to the System.Web.Extensions.dll be made available in the same way that the source for the AJAX extensions for ASP.NET 2.0 was made available, or will it become a part of the main .NET framework (and therefore available through the VS2008 IDE instead)?

3.) Can you provide an example of how we might use a server side control to generate the drop down list or a textbox (a la WebForms) along with the pro's and con's of each approach? Personally, I do not like the old ASP <%= ... %> syntax; but if there is a good reason to use it then I am willing to change that opinion.

Thanks and looking forward to the CTP drop.

Martin.

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 9:07 AM by lkempe

Hi Scott,

Nice to see you and your team going on that direction!

What can we expect concerning PageFlow ? I know that a project was started quite some time ago and we didn't hear anything about it anymore. I guess it is due to the MVC Framework, or? So do you consider such a pageflow solution for MVC ?

Now that we have a clear separation of the Model, Controller and View do you see a re-use of this architecture, let say on Silverlight 2.0 ?

I have implemented my portal (www.TechHeadBrothers.com) using WebParts, how do you see MVC and WebParts working together ?

Regards

Laurent Kempé

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 9:15 AM by Martin Robins

Slightly off topic, however I notice that within your helper methods you are using the ToList LINQ extension method. I have been trying to use this within my own applications, however whereas if I use the "from .. in .. select" syntax directly and assign the "var result" as a datasource for a control the resulting list supports sorting, the result of the ToList never supports sorting. This makes it very difficult for me to move all of the data access out of my UI. Is there an alternative that allows sorting?

Martin.

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 9:18 AM by Peter

What if I had to add more data? I'd have to edit both New and Edit views and it is a sign of repeating yourself. From my experience, New and Edit views are the same, only the values in New view are blank

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 9:37 AM by Jeffrey Palermo

The view helpers will be really nice.  By the way, if there are proposed view helpers that don't make the cut for the product or the toolkit, let me know, and we'll get them on the list for MvcContrib.

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 9:49 AM by Mads

Hi Scott,

Another great article!

I have some concerns over the URL scheme.

I know these extensionless URLs will probably run with no hazzle on IIS7, but if you use IIS6 or so, you'll have so do some configuring in the IIS Manager, right?

So, if you don't have access to the IIS Manager, you'll be forced to put your views in the root of the website (like /ProductNew.aspx), unless you can live with URLs like /Views/Products/New.aspx?

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 10:03 AM by John Campion

Scott, thanks for theses great posts - This is an exciting option for ASP.NET.  

What about using one view for both editing and adding, is that possible?

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 10:20 AM by Alexander Gornik

Scott, about the UpdateFrom method: does it map strings to strongly typed properties automatically? What if i'd like a user to enter a datetime into a textbox in a form?

And how validation is intended to be done in this scenario?

Would be nice to see a blog post covering validation in MVC framework, especially if you will show how validation can be done

using Validation Application Block (the only nice block from EntLib out there) and validation code in the model. Ideally with some heavy ajax magic, ala ServerSideValidationExtender (www.pnpguidance.net/.../ServerSideValidationExtenderASPNETServerSideValidationAJAXPartialPagePostBack.aspx)

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 11:08 AM by David Brown

I must admit that I never really paid much attention to ASP.NET MVC, mostly because I wasn't sure if it was going to be a usable as other frameworks such as Ruby on Rails. However, your article has really opened my eyes.

Thanks for writing this!

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 11:10 AM by John Chapman

Scott,

great post, but I have one minor question about your NorthwindDataContext implementation where you are writing your queries.

Why does GetCategoryById(int) use First whereas GetProductById(int) uses Single.  Shouldn't both methods really be using the Single() method?  I assume the Ids are the primary keys of both entities.  If more than one item is returned by GetCategoryById wouldn't that indicate a problem, and hence an exception?  Or is there a reason why these are different?

Thanks,

John Chapman

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 11:53 AM by Mike

I think that the naming of Html.TextBox and Html.Select is not consistent. The first uses an ASP.NET control name and the second uses HTML tag name.

That being said, is it possible to use one form for both the New and the Edit actions? If the Html.TextBox and Html.Select methods will not have a problem with null values in the overloads that would otherwise prefill/preselect the passed in value, then I think it should not be a problem. I'll have to try that out.

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 12:01 PM by Simon Green

>>> No - that is for the ADO.NET entities bits (which is something different).  Keep an eye on www.asp.net in a few hours - the ASP.NET 3.5 Extensions Preview (which includes MVC) will be posted there shortly.

I'm sure I'm not the only one who's been looking forward to getting my hands on this so I really appreciate you guys working over the weekend to get it ready.

Thanks!

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 12:10 PM by MichaelD!

YES YES YES!  Fanfreakin'tastic amazing stuff here Scott!  But we must do something about those escape tags... they sure are ugly.  Server controls ASAP!!! :)

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 12:22 PM by Roger

Hi Scott,

Could you explain why you would want to use a helper method like Html.Select or Html.TextBox rather than creating a standard select or input tag with a runat=server attribute, and then doing the databinding in the code behind?

It seems like with the latter approach a designer would have more flexibility to manipulate the markup, such as manipulating style attributes, attaching events, setting the id, etc, while also separating the presentation code from the presentation markup.

Is this no longer possible with the MVP approach?

Thanks,

Roger

# MVC.net Release TODAY!

Sunday, December 09, 2007 12:42 PM by SquaredRoot

MVC.net Release TODAY!

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 12:52 PM by Troy Goode

Hi Scott,

I just wanted to give you a heads up that permalinks for your comments are not working. The pound/hash symbol next to a comment title lists the proper comment ID (I imagine) but there is no anchor tag (<a name="5426401" />) for the browser to scroll to. There have been a couple times in the past few days that I've wanted to link to one of your comments, but had to repost them to my own blog. Just an FYI, I'm sure you have more important things to worry about right now!

Troy Goode

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 1:09 PM by Mark S. Rasmussen

How will validation function using this scheme? Since we can no longer use the standard validation controls, where does the validation responsibility lie, besides on the client side - is the New() controller supposed to validate and send back to the Edit() controller along with validation exceptions?

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 1:19 PM by Agrinei

This is really great! Will the HtmlHelpers be able to generate the basic (and tedious) html constraints and validation like maxlength, required fields validation, date validation, etc, based on the database constraints ? ViewData could be built to hold some metadata got from the DataContext...

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 1:30 PM by James Hancock

These articles are very good! I really appreciate the insite and I can see how for professional programmers this can be vastly better than the current page model in ASP.NET

Here's a request for an article:

How to use asp.net server controls and third party controls with MVC.net effectively with AJAX.NET.

Basically I'd like to see how we can hook up AJAX.net and existing 3rd party asp.net controls and make them work effectively with this methodolgy.  The default controls are great and all, but they're really limited. Nothing like using Telerik or DevExpress controls to really spruce up the UI of your web site and I don't want to be cut off from those with MVC.

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 1:31 PM by Kevin Daly

Hi Scott,

Is the mapping of form field names to properties by UpdateFrom case-sensitive?

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 1:51 PM by ScottGu

Hi David,

>>>>>>> Question, how will the framework handle file uploads? It just occured to me that in your example its a product your adding/updating and noticed there was no image upload functionality.

The Controller class has a IHttpRequest object that has the same object model as HttpRequest object today.  So one approach you can use is to access uploaded files via the Request.Files[] collection.  This then gives you helper methods to retrieve the stream and/or save to disk.

I don't know if the helper methods automatically map posted content to byte[] properties on objects.  I suspect they don't today - but that might be an interesting scenario to consider adding support for.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 1:53 PM by ScottGu

Hi Chris,

>>>>>>> What's the LINQ to SQL support like with using dates? I remember when I was trying to use date/times with LINQ it didn't like it at all and came up with all sorts of errors. It'd be good to essentially timestamp when new products were added or edited and I was wondering if using LINQ/MVC would make this a little easier?

I havne't had problems with date/times with LINQ before myself.  One scenario you can also do with it is to mark a column as a timestamp - in which case LINQ to SQL can not only track it, but also enable you to use optimistic concurrency for changes.  I need to put it on my list of things to-do to write a sample that does that.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 1:55 PM by Jonel

Very well thought and detailed article Scott. I can't wait for the preview bits.

Thanks,

Jonel

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 1:56 PM by ScottGu

Hi Vijay,

>>>>>>>> However, liviu raises good questions about Sub-Controllers, Composite Views and AJAX scenarios. How Will the MVC framework address the complex wiring of different parts of a page to different controllers for async updates?? My brain hurts thinking about it, yet I have implement these portal pages all the time cos our customers demand it.

The first ASP.NET MVC Preview allows you to call RenderView (for example: RenderView("Edit")) and have it apply to either a .aspx viewpage or a .ascx viewusercontrol.  This ends up being really useful for scenarios where you are doing AJAX callbacks and want to refresh a portion of a page.  These callbacks could either be to the same Controller that rendered the origional page, or to another Controller in the project.

We don't have all the AJAX helper methods yet for this - but you could roll them yourself today.  We'll obviously be releasing an update that does include them in the future.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 1:57 PM by David Pio

When populating the dropdowns, you pass in to the Html.Select method a ViewData.Categories or a ViewData.Suppliers respectively.  Yet the emitted HTML automagically knows to use the CategoryName and CompanyName property.  How is this defined?

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:00 PM by ScottGu

Hi Martin,

>>>>>>> Is it fair to read into this that the extensions in the MVCToolkit.dll will eventually be integrated into the main System.Web.Extensions.dll or will they always be in a seperate assembly?

Yes - our plan is to roll them into the MVC framework assembly in the future.  We didn't have time to test and polish them up as much as we'd like (some where still being written a few days ago <g>), which is why they are in a separate assembly today.  

>>>>>>>>> Will the source to the System.Web.Extensions.dll be made available in the same way that the source for the AJAX extensions for ASP.NET 2.0 was made available, or will it become a part of the main .NET framework (and therefore available through the VS2008 IDE instead)?

Yes - we'll make the source to the MVC Framework available (probably both ways you listed above).

>>>>>>>>> Can you provide an example of how we might use a server side control to generate the drop down list or a textbox (a la WebForms) along with the pro's and con's of each approach? Personally, I do not like the old ASP <%= ... %> syntax; but if there is a good reason to use it then I am willing to change that opinion.

The main reason I showed the <% %> syntax in this post was that we don't have the server-side MVC control equivalents available yet for this dropdown and text scenario.  That is on our roadmap to-do though - at which point you don't need to necessarily use the <% %> syntax.

In general what we've found is that some developers hate the <% %> syntax, while others prefer it (and feel that controls get in the way).  We want to make both sets of developers happy, and will have options for both. :-)

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:04 PM by ScottGu

Hi Laurent,

>>>>>>> What can we expect concerning PageFlow ? I know that a project was started quite some time ago and we didn't hear anything about it anymore. I guess it is due to the MVC Framework, or? So do you consider such a pageflow solution for MVC ?

We should be able to layer PageFlow on top of the MVC Framework pretty easily now.  One of the reasons we haven't productized it yet was that we thought there should be dependencies on the MVC framework from PageFlow.  Rather than implementing all the semantics for things like routing and control/view separation it made more sense to bake those into MVC, and then have PageFlow provide higher level services on top.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:05 PM by ScottGu

Hi Martin,

>>>>>>>> Slightly off topic, however I notice that within your helper methods you are using the ToList LINQ extension method. I have been trying to use this within my own applications, however whereas if I use the "from .. in .. select" syntax directly and assign the "var result" as a datasource for a control the resulting list supports sorting, the result of the ToList never supports sorting. This makes it very difficult for me to move all of the data access out of my UI. Is there an alternative that allows sorting?

You might want to just return your questies as IQueryable<T> results.  These should support the ability to perform additional LINQ filter and sort expressions on them.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:07 PM by ScottGu

Hi Peter,

>>>>>>>> What if I had to add more data? I'd have to edit both New and Edit views and it is a sign of repeating yourself. From my experience, New and Edit views are the same, only the values in New view are blank

You can ceretainly write it that way using the MVC framework.  There are a few conditional cases which you might write differently depending on the scenario - which is why I decided to go with two templates for this sample (I thought people would find it easier to understand that way).

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:08 PM by ScottGu

Hi Mads,

>>>>>>> I know these extensionless URLs will probably run with no hazzle on IIS7, but if you use IIS6 or so, you'll have so do some configuring in the IIS Manager, right?  So, if you don't have access to the IIS Manager, you'll be forced to put your views in the root of the website (like /ProductNew.aspx), unless you can live with URLs like /Views/Products/New.aspx?

One approach you can do is to change the main routing rule in your Global.asax to use a routing rule format like: [Controller].mvc/[Action]/[Id]

We register a .mvc extension when installing the ASP.NET MVC package.  Once you do this things should work fine on IIS6 (without requiring you to register or use an ISAPI filter for extensionless URLs).

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:09 PM by ScottGu

Hi John,

>>>>>>> What about using one view for both editing and adding, is that possible?

Yep - that is definitely supported.  I used two separate view templates above mainly just to keep things simpler and to help get across that you can have a controller easily use multiple view templates if you want.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:12 PM by ScottGu

Hi Alexander,

>>>>>>> Scott, about the UpdateFrom method: does it map strings to strongly typed properties automatically? What if i'd like a user to enter a datetime into a textbox in a form?

The UpdateForm helper uses TypeConvertors to convert values from string to data-types.  So all of the built-in .NET types (including DateTime) should work - you can also register your own custom TypeConvertors to help with custom types.

>>>>>>>> And how validation is intended to be done in this scenario?

I'll do some posts in the future about validation and ways to handle this.  The UpdateFrom extension method now raises an exception when mapping failures occur - and you can use this to redisplay forms with UI indicating the failures.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:15 PM by ScottGu

Hi John,

>>>>>>> Why does GetCategoryById(int) use First whereas GetProductById(int) uses Single.  Shouldn't both methods really be using the Single() method?  I assume the Ids are the primary keys of both entities.  If more than one item is returned by GetCategoryById wouldn't that indicate a problem, and hence an exception?  Or is there a reason why these are different?

Good catch.  The reason isn't a very good one - just that it was late at night when I wrote it. :-)

In general when looking up objects based on their primary key you should use Single().  This indicates that there should be one and only one result from the query (and will raise an exception if there is more).  First() indicates that you want to return first first object in the sequence returned.  

Since we are looking up Products and Categories based on primary key we can use Single() - since it is guarenteed that there aren't two rows with the same primary key.  Using First() in this example doesn't cause problems - but for absolutely correctness I should have using Single().

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:17 PM by ScottGu

Hi Mike,

>>>>>>> I think that the naming of Html.TextBox and Html.Select is not consistent. The first uses an ASP.NET control name and the second uses HTML tag name.

The textbox in HTML is <input type="text"/>.  Technically the helper should probably be Html.InputText - although that seemed a little less discoverable.  We'll look at it more though to see if it should be more consistent.

>>>>>>>> That being said, is it possible to use one form for both the New and the Edit actions? If the Html.TextBox and Html.Select methods will not have a problem with null values in the overloads that would otherwise prefill/preselect the passed in value, then I think it should not be a problem. I'll have to try that out.

Yes - you should be able to share the same view to use for both New and Edit actions.  

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:20 PM by Eric

1) There is an awful lot of repeated code and markup between the Edit and Create Views/Controllers.  If you add in data validation, there will be even more repeated code.

2) You should do a future posting on integrating MVC and Web Forms pages.  With the URL rewriting, how would this work?

3) I'm having trouble figuring out Forms Authentication will work with the MVC URLs.  That would be a great topic of a future post.

Thanks for the time and effort you and your team put into ASP.NET!  :)

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:20 PM by ScottGu

Hi Roger,

>>>>>>> Could you explain why you would want to use a helper method like Html.Select or Html.TextBox rather than creating a standard select or input tag with a runat=server attribute, and then doing the databinding in the code behind?  It seems like with the latter approach a designer would have more flexibility to manipulate the markup, such as manipulating style attributes, attaching events, setting the id, etc, while also separating the presentation code from the presentation markup.

A lot of it comes down to personal preference - some people hate inline code, others don't like declarative templating since they feel that abstracts the real intent.  At the end of the day both are perfectly valid - it really comes down to developer preference.

The first ASP.NET MVC CTP doesn't have declarative MVC form control helpers yet (the current <asp:textbox> only works with web forms postback scenarios).  This is something we are planning to enable in the future - but you'll need to wait for a future preview build to get support this.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:22 PM by ScottGu

Hi Mark,

>>>>>>> How will validation function using this scheme? Since we can no longer use the standard validation controls, where does the validation responsibility lie, besides on the client side - is the New() controller supposed to validate and send back to the Edit() controller along with validation exceptions?

I'll do a blog post on validation in the future that covers this more.  On the server side you'll typically validate at the ORM level, and if an error occurs raise an exception.  The controller can then handle this and redisplay the view with populated values.  I'll show how to-do this in a future post.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:23 PM by ScottGu

Hi Agrinei,

>>>>>> This is really great! Will the HtmlHelpers be able to generate the basic (and tedious) html constraints and validation like maxlength, required fields validation, date validation, etc, based on the database constraints ? ViewData could be built to hold some metadata got from the DataContext...

Yes - this is something we are looking to enable.  You'll see more of this when we talk about data scaffolding.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:23 PM by Maciej Kuczara (ABB)

Hi Scott, another interesting article, i know maybe it's too soon to ask.. but what about AJAX support? Could you give us some dates when AJAX and server-side MVC controls will be available for usage.

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:24 PM by ScottGu

Hi Kevin,

>>>>>>> Is the mapping of form field names to properties by UpdateFrom case-sensitive?

No - I believe the property mapping is case insensitive.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:26 PM by Ben

Love the work that you guys are doing in this area. LINQ and MVC seem like a match made in heaven.

However, I am still concerned with support for rich web application development. The views you have been describing are a little simple. Forgetting validation, what happens when we want to put significant chunks of interrelated data on a single page? Do we simply flood the ViewData collection and pray? What design patterns do you encourage for this scenario?

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:26 PM by ScottGu

Hi James,

>>>>>>>> Here's a request for an article:  How to use asp.net server controls and third party controls with MVC.net effectively with AJAX.NET.  Basically I'd like to see how we can hook up AJAX.net and existing 3rd party asp.net controls and make them work effectively with this methodolgy.  The default controls are great and all, but they're really limited. Nothing like using Telerik or DevExpress controls to really spruce up the UI of your web site and I don't want to be cut off from those with MVC.

Yep - that is definitely something we are looking to enable.  We'll be working with third party control vendors as well as the broader community to make sure there is a great way for people to extend the built-in UI helper functionality with even richer options.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:29 PM by panjkov

i see that you are online now... will these bits be released today (or tonight, it is 8pm here in banjaluka, bosnia&herzegovina)

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:31 PM by Jonel

Today is like waiting for the Leopard Mac OS X to hit the store! I can't wait anymore for the preview!

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:41 PM by ScottGu

Hi David,

>>>>> When populating the dropdowns, you pass in to the Html.Select method a ViewData.Categories or a ViewData.Suppliers respectively.  Yet the emitted HTML automagically knows to use the CategoryName and CompanyName property.  How is this defined?

I was wondering if anyone would ask (since I asked the same thing as I was writing the code - and at first couldn't understand how it magically worked).

By default if you don't explictly indicate the textfield and valuefield to use, it will default to using the first property on the object for the valuefield, and the second for the textfield.  This works suprisingly well with a lot of ORM and database schemas.

Of course, for scenarios were it doesn't just used the overloaded version of the method does allows you to explictly specify the properties to use for this.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:44 PM by ScottGu

Hi Maciej,

>>>>>>> what about AJAX support? Could you give us some dates when AJAX and server-side MVC controls will be available for usage.

This is definitely coming and a priority we are working on.  I don't have an exact ETA on getting official AJAX support in the bits - but I suspect people will have helpers you can download and use to enable it pretty quickly.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:46 PM by Matthew

I love the UpdateFrom() Extension method but the problem I see is now your form fields' names have to be tightly coupled to the property names of your object.  If I change one property name on my object, now I have to go to every form field and change those names.  Is there a way I can pass some kind of dictionary-key-to-property-name map into the UpdateFrom() method?

Do the properties on the object have to have get and set accessors, or can they have just set accessors?

How deep down the object graph does UpdateFrom() go?  If I have a textbox named Supplier.Address.Street, will it fill in he street property on the address property of the supplier object?  

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 2:52 PM by James Hollingworth

Hi Scott,

I was wondering, is there any method of data binding an array of objects, e.g. if you had a page which edited 10 products at the same time rather that just one. In monorail, you can would use the syntax "product[count].Name, product[count].ID...", is there a similar functionality with MVC? Also is there any method for having multiple buttons in one form doing different things? e.g. one button to save, one to delete...

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 3:04 PM by Josh Hurley

Great work on the MVC model, it is a clean and intuitive model that appears to scale well. My only recommendation is that your actions (verbs) appear after the ids (nouns), e.g. [Controller]/[Id]/[Action]/

That would keep the architecture noun focused, opposed to verb focused. With this approach you can easily build an administrative interface on a public read-only site by adding verbs such as /edit/ or /delete/ at the end of your URL. A simple security rule can be added to the Controller that says ignore all Verbs after a noun, such as category or product, if user is not part of an administrative group.

Examples of what I propose are:

/Domain/Products/Category/[CategoryID]

/Domain/Products/Category/[CategoryID]/Edit/

/Domain/Products/Category/[CategoryID]/Delete/

/Domain/Products/[ProductID]

/Domain/Products/[ProductID]/Edit/

/Domain/Products/[ProductID]/Delete/

More complex MVC models might require a verb before a noun, but the second noun would be helper of the verb, which would still appear after the primary noun. For example:

/Domain/Products/Category/[CategoryID]/AssociateProduct/[ProductID]

In this example a product would be associated with a Category. From a security standpoint, the same simple security rule works because the verb appears after the first noun.

I look forward to reading more as you work on this model.

Best,

Josh.

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 3:08 PM by PBZ

So, is there going to be an equivalent to ViewState or are we supposed to go back to the old days and inconvenience the user, by losing whatever he/she typed, for the sake of the underlying system's design?

# rascunho &raquo; Blog Archive &raquo; links for 2007-12-09

Sunday, December 09, 2007 3:20 PM by rascunho » Blog Archive » links for 2007-12-09

Pingback from  rascunho  &raquo; Blog Archive   &raquo; links for 2007-12-09

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 3:41 PM by Curt Hagenlocher

Aarrgh!  Someone stop me from hitting F5 on the ASP.NET website every five minutes...

# re: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios

Sunday, December 09, 2007 3:42 PM by Marco von Frieling

Hello Scott!

The MVC Framework looks really nice! When I heard the first time about it, I thought, what's that new stuff from Microsoft. Do I really need it? But after reading your posts part 1 to 3, I thougt, that's mostly what I'm looking for since years.

But I have some questions about /considerations for the framework:

1. How does the installation work on the server (I didn't found the download yet on www.asp.net), is it just one or some assemblies which must be referenced in the project and deployed with it in the bin folder, or must it be installed by the web hoster?

2. With ASP.NET 2.0 I'm using themes intensively, but I'm not a fan of skins. For me it is too much overhead to define a skin for a control just for choosing an image from the current theme, and often which image must be choosen depends on dynamically values or data. So I've written a helper class which takes a path like "~$/resource.ext", resolves the "~$/" prefix (if exists) to the current theme path or a shared fallback images folder, resolves the "~/" using ASP.NET functionality and returns the application rooted path for the resource. Is something like this supported with MVC?

3. In your MVC presentation (video from Scott Hanselman) you told that it is possible to incorporate two or more MVC projects into one single site and the only thing you