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

125 Comments

  • 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 ;) ?

  • is this correct link for asp.net extensions preview that will be shipped (today?)
    http://go.microsoft.com/fwlink/?LinkId=105896
    (taken from http://www.hunterstrat.com/news/2007/12/07/microsoft-releases-adonet-entity-framework-aspnet-35-extensions-previews)

    it is pointing here
    http://www.microsoft.com/downloads/details.aspx?FamilyId=A9C6BC06-B894-4B11-8300-35BD2F8FC908&displaylang=en

  • 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

  • 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

  • *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.

  • it is also announced in ms presspass...
    "the ASP.NET 3.5 Extensions preview will be available at http://go.microsoft.com/fwlink/?LinkId=105896."

  • 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!

  • 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

  • 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.

  • 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é

  • 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.

  • 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

  • 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.

  • 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?

  • 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?

  • 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!

  • 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

  • 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.

  • >>> 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!

  • 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!!! :)

  • 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

  • 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 () 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

  • 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?

  • 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...

  • 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.

  • Hi Scott,
    Is the mapping of form field names to properties by UpdateFrom case-sensitive?

  • 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

  • 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

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

    Thanks,
    Jonel

  • 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

  • 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?

  • 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 ), 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

  • 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

  • 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 results. These should support the ability to perform additional LINQ filter and sort expressions on them.

    Thanks,

    Scott

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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 . 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

  • 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! :)

  • 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 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

  • 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

  • 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

  • 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.

  • 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

  • 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?

  • 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

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

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

  • 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

  • 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

  • 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?

  • 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.

  • 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?

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

  • is the 3.5 Ext preview being released today for sure? I read that you said early sunday and it is now almost late sunday or mid sunday depending where you are at in the us.

    Thanks, MIke

  • Hi Scott,

    Will the CTP work in Visual Web Editor Express?

    Thanks,
    Mladen

  • Arghhhh! The suspense is killing me!

    All i want for Xmas is my MVC :-)

    David

  • David (Dave "The Ninja" Lawton),

    Aww come on, now you've jinxed it. We wont see it until the 25th now.

  • Very good series of articles Scott!

    I was wondering if we could get an idea of the official "roadmap" for asp.net mvc? Specifically, I'd like to know what features the team plans to release on what dates ... ultimately, when this thing will RTM. As I'll be evaluating mvc and monorail for an upcoming app, this kind of information would really be helpful in determining which direction to go.

    thanks again!

  • For anyone looking for the release you can find the download over here, http://www.microsoft.com/downloads/details.aspx?FamilyID=A9C6BC06-B894-4B11-8300-35BD2F8FC908&displaylang=en

  • Hi Scott. Was the MVCToolkit dll included with the preview release and if so where is it located? Can't find it so I can't reference it.

    Thanks, Mike

  • I downloaded the preview, and tried using a Repeater control like some of your sample code shows, and it does not seem to work. The control does not even appear to exist as far as the code-behind is concerned. What am I doing wrong?

  • Hi Scott. After i added in the server controls to the viewpage design view, i could not build the solution since cannot find the control in code behind. Now i am looking for some runnable samples that are using the "DataBinding" style rather than the inline codes.
    Did i miss somthing important? or the current CTP just doesnot allow using server controls in view?

    thanx

  • Great article indeed.

  • Hi Mladen,

    >>>>>>> Will the CTP work in Visual Web Editor Express?

    The CTP for most of the ASP.NET Extensions Preview features will work in VWD Express. The MVC framework today uses a web application project approach (since this lends itself best to unit testing). Class libraries and web application projects don't currently work with VWD Express (which means you can use it for this preview). We are going to be doing a VWD refresh the first half of next year, though, will will enables this support. You'll be able to use the MVC approach then with it.

    Hope this helps,

    Scott

  • Hi John and Sitem00n,

    >>>>>>> I downloaded the preview, and tried using a Repeater control like some of your sample code shows, and it does not seem to work. The control does not even appear to exist as far as the code-behind is concerned. What am I doing wrong?

    There is an issue with the default file templates that you use to create view pages with the MVC project. They unfortunately by default don't generate the .designer.cs/.vb files that are used by the code-behind to get intellisense for controls - which is why you are running into the issue you are seeing.

    The good news is that this is easy to fix. Just select your file in the solution explorer, right click, and choose the "Convert to Web Application" context menu option. This will generate the .designer file for you. From that point on, all changes you make to the .aspx file will be reflected in the code behind, and you'll be able to databind declaratively using the control.

    Hope this helps,

    Scott

  • Nice work Scott. Waiting for more articles on the same.

  • >>>>> The textbox in HTML is . 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.

    My thought on this is that it should be consistent internally, not necessarily with HTML naming. You mentioned that Microsoft will also have controls for ASP.NET MVC, I think the naming of controls should be in sync with the naming of these methods. So by all means use Html.TextBox(), but then also use Html.DropDownList() and at the same time have and

    What's the story going to be for third party control developers? Have you heard from partners (such as ComponentArt) that they plan to support this framework with controls?

  • >>>>> 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 want to just point out that I would _really_ like to associate the error with the originating inputs, so that I can style them differently or display the error messages next to the inputs. I hope your team will look into this. Thanks!

  • It becomes interesting...
    Just some question: controller classes must be in the main project? i.e. there is a way to have a separated assembly with controlles and then configure application to use it?

    Regards

  • Last post, I promise!

    >>>>> 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.

    That is _exactly_ the thing that I'm looking for in this framework, excellent! I thought I would net to switch to Ruby on Rails to get these kind of smart conventions, but it seems your team has done its research. Good job!

  • Hey Scott,

    I have Visual Studio 2008 Professional and there's no MVC Web Application Template on the create new project options, is there any extension to be installed for it to appear in the create new project options? If there is where can I get it?

    Thanks

  • Hello. I like the ability to have full control over HTML generation, but seems like html, generated with helpers, is not properly indented.

  • I have two questions:

    1) Lets say i want my pages to inherit from ViewPage, can i do that without code behind? just using the declarative asp markup?

    2) Is it possible to create two websites in IIS6 one named mydomain.com and one static.mydomain.com and create a wildcard mapping to mydomain.com and reference all static files through static.mydomain.com so i should be able to have truly clean URL's under IIS6 and still let IIS handle static files?

    Thanks

  • Hi Scott,
    1)A few questions: how a binding with a repeating items would affect mapping for update/saving purposes?
    2)Is it possible to control the mapping process and not only rely on string representations? I don't find auto-magic way always working for me, and with different naming conventions - you need more customization. Also possible unit testing of the mapping.
    3)ASP.NET has a great section of how-tos. Would be nice to have something like that for MVC as well.

    Thank you.

  • @ Josh Hurley re: verbs and nouns

    I was just watching the screencast that Scott Hanselman has done about MVC and he switches the actions around in the URL just by changing the URL format in the global.asax.cs. E.g. /home/edit/5 can also be /home/5/edit

  • Hi Scott,

    Great work on the article - very informative. The thing I would greatly appreciate you to explain more in detail when you do cover the Validation side of things is:
    a) How to best reuse the business rules on the server-side (both at the database and model level) so that things like product Descrition cannot be blank and price must be greater than $0 and less than $500 can be reused across the New/Create and Update/Edit pages
    b) As people have asked in previous comments/posts - would be great to see an example of how to reuse the same page for New and Edit, adding Copy capability to the Product Listing page where Copy would go to the Create/New page with all values prefilled and then create the Product in the database
    with a new ProductID assigned.
    c) The last comment with regards to validation messages is - once a new product is added, what is the best approach to show a message on the product listing page that shows the database assigned ProductID for the new product that was just created ?

    Great work from your team!!!

    Thanks

  • I'll check out the screencast with Scott Hanselman. Thanks.

  • Great work Scott!

    What do you think about automatically handling HTML caching?

  • It might be acceptable for non-interactive websites, but writing a web application using this method is almost impossible.
    The only benefit I can see here is the nice url mapping, but it doesn't worth to sacrifice the power of server-side controls and reusability of UI components.

  • Instead of creating two different actions for New and Create, I would like to have an overloaded New - if parameter-less New(), RenderView("New"); if parameter-ful New(productName, categoryId, ...), create the product and redirect back to the listing. Is this possible?

  • Hi Scott,

    Thanks for your informitive series of articles.

    Please consider a version of UpdateFrom() that does not raise exceptions and just returns a collection of validation errors. Exceptions are expensive for simple validations I think that is why the tryParse methods were addes to FCL. Also if exception is raised immidiatly after encountering the first validation failure then you get the errors one at a time instead of all at once.

    Thanks.

  • Hi 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?

    Right now there isn't a dictionary-key-to-property-name map - but you could ceretainly add one. Alternatively, you could build a a dictionary that took Request.Form and converted it to another dictionary of values. You could then just pass this to the UpdateFrom method.

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

    I believe the properties can just be setters if you want.

    >>>>>>> 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?

    For the first CTP I think it just works against top-level properties - but I believe the plan going forward will be to support multiple layers deep.

    Hope this helps!

    Scott

  • Hi James,

    >>>>>>> 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...

    This isn't supported just yet with teh built-in UpdateForm - but I definitely agree it is a good idea. Can you post a suggestion on this to the MVC forum: http://forums.asp.net/1146.aspx

    Thx!

    Scott

  • Hi Josh,

    >>>>>>>> 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.

    Thanks for the suggestion Josh. You can do this today by creating your own custom route registration. In the next preview I believe Route will be extensible so that you could also create a single resource route that supports these semantics.

    Thanks,

    Scott

  • Hi Wayde,

    >>>>>>> I was wondering if we could get an idea of the official "roadmap" for asp.net mvc? Specifically, I'd like to know what features the team plans to release on what dates ... ultimately, when this thing will RTM. As I'll be evaluating mvc and monorail for an upcoming app, this kind of information would really be helpful in determining which direction to go.

    We don't have a formally published roadmap just yet - we will hopefully publish one early next year though.

    Thanks,

    Scott

  • Hi Mike,

    >>>>>>> My thought on this is that it should be consistent internally, not necessarily with HTML naming. You mentioned that Microsoft will also have controls for ASP.NET MVC, I think the naming of controls should be in sync with the naming of these methods. So by all means use Html.TextBox(), but then also use Html.DropDownList() and at the same time have and

    Yep - definitely agree that the helpers and controls should be named consistently.

    >>>>>>>>> What's the story going to be for third party control developers? Have you heard from partners (such as ComponentArt) that they plan to support this framework with controls?

    I believe control vendors will be interested in supporting this model (they like selling controls!). A number of them are in our early adopter program now and working with us on this.

    Thanks,

    Scott

  • Hi Mike,

    >>>>>>> I want to just point out that I would _really_ like to associate the error with the originating inputs, so that I can style them differently or display the error messages next to the inputs. I hope your team will look into this. Thanks!

    I believe this is supported with the exceptions that are raised.

    Thanks,

    Scott

  • Hi James,

    >>>>>>> 1) Lets say i want my pages to inherit from ViewPage, can i do that without code behind? just using the declarative asp markup?

    It is possible today - although the syntax for the type name is pretty hard to read. We are going to look at hopefully making the syntax for this easier in the future.

    Thanks,

    Scott

  • Hi Sean,

    >>>>>>> 1)A few questions: how a binding with a repeating items would affect mapping for update/saving purposes?

    You could generate a separate mapping for each item - just pass in different values to the helper and it will create a different URLs.

    >>>>>>>> 2)Is it possible to control the mapping process and not only rely on string representations? I don't find auto-magic way always working for me, and with different naming conventions - you need more customization. Also possible unit testing of the mapping.

    The MVCToolkit.zip helpers have a Html.ActionLink method that allows you to pass in a Lambda expression. This avoids the need to use strings and get type checking.

    >>>>>>>> 3)ASP.NET has a great section of how-tos. Would be nice to have something like that for MVC as well.

    Yep - we'll definitely be doing lots of videos on this.

    Thanks,

    Scott

  • Hi Anthony,

    >>>>>>>> First let me say that I think the MVC extensions are great and I have been looking forward to seeing the first bits in action. I also like that MS is starting to offer optional design patterns to work with in the web world. I guess my only reservation with this new framework is the maturity of it. Admitting that this is the first public release and I'm sure things will get more polished as time goes on, but a part of me feels reserved to move towards this because of the lack of features we have with the WebForm world. My fear is that I would start building an application with this new framework and once I really get into it realize oh crap this and that and this is missing... Am I alone on this thought?

    That is ceretainly a fair concern. Overtime the MVC framework will get richer - but if you are looking for something that is mature and feature rich today WebForms has a lot of advantages.

    Hope this helps,

    Scott

  • Hi Mad,

    >>>>> Great work on the article - very informative. The thing I would greatly appreciate you to explain more in detail when you do cover the Validation side of things is:

    This is on my list of things to cover in the future. :-)

    Thanks,

    Scott

  • Hi Paul,

    >>>>>> 2) Ability to have compile-time checking of URLs, basically it would be wonderful to have some intellisense and checking that controller actions are valid. - Is this possible using the currently implemented features? The fact that string literals are used in the RedirectToAction methods suggests probably not.

    We will have type-safe methods like RedirectToActionc.Edit(5)) that utilize the new lambda features in VS 2008 and .NET 3.5 to get type-safety. You can learn more about these in my blog post here: http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx

    Hope this helps,

    Scott

  • Hi Maxtorog,

    >>>>>>> What do you think about automatically handling HTML caching?

    Yep - we'll have full output caching support. In fact, the existing output caching features in ASP.NET today work fine with MVC.

    Thanks,

    Scott

  • Hi Roman,

    >>>>>> Instead of creating two different actions for New and Create, I would like to have an overloaded New - if parameter-less New(), RenderView("New"); if parameter-ful New(productName, categoryId, ...), create the product and redirect back to the listing. Is this possible?

    I don't believe we currently support overloading action methods on our default Controller base class. It is a good suggestion for the future though.

    Thanks,

    Scott

  • Hi Areg,

    >>>>>>> Please consider a version of UpdateFrom() that does not raise exceptions and just returns a collection of validation errors. Exceptions are expensive for simple validations I think that is why the tryParse methods were addes to FCL. Also if exception is raised immidiatly after encountering the first validation failure then you get the errors one at a time instead of all at once.

    Good suggestions. Can you post them here: http://forums.asp.net/1146.aspx Rob Conery (who is working on this method) would be a great person to bounce them off of.

    Thanks,

    Scott

  • Thanks very much for the clarification Scott, that's great news!

  • Hi Scott,

    Couple of questions..

    1. Is there likely to be an equivalent to ViewState so that we don't loose the user's typed data every time we "post back" to an action?

    2. Is there likely to be support from framework items like Rails' "Flash" as a temporary store of short messages that can be passed around? eg. for notifications set Flash["msg"] to something that can be displayed in the view.

    3. Any likely plans in the roadmap for scaffolds and migrations?

    Thanks

  • Hi Scott,

    The sample code for Part4 doesn't seem to contain what you showed in the previous 3 parts, where can I find the code for the entire series?

    Thanks,
    Ray.

  • So what happens when a user Adds a new Product, returns to the list, and hits the Back Button. Are they going to get the dreaded "Repost Form Data" problem? I'm looking for a way to work around this.

  • Hello Scott,
    I can see Linq is being used here, great!....I thought I read somewhere that Subsonic was going to be used for the M in the ASP.net MVC framework...any clarification about that?
    thanks

  • Hi Scott

    If I'm jumping the gun here please let me know, but so far I haven't seen the issue of viewstate and postback information addresses.

    For example, if in your demo the Supplier list was dependant on the Categories list i.e. only suppliers for the selcted category would be displayed, how would this be handled in the context of your example, and how would the product name and price info be persisted across the posts?

    Please keep up the excellent work.
    Thanks.

  • This is looking very good Scott. Can you explain how to handle validation that you don't know about until you are in the controller? For example if I want to do a custom validator that does some sort of server validation only within the save method or a save fails and I want to tell the user. What is the best way to return to the view, display a notification and show the invalid fields? Thanks for the help.

  • Hi Scott,

    If the items of select Control B dependend on selected item of select control A,
    how to deal with this kind of problem?

  • Hello.

    Thanks for your answers. But one question is still open:

    >>>>>>>> 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 [...]. Is it possible to share "visual" components between different MVC projects beeing incorporated to one website. What I mean is, can I have a project (MVC or simple Web Application project) "CompanyCI" containing all my .master and lots of .ascx files which then I can use in the MVC projects?

    >>>> Yes - this will be supported. You can load your views from any folder.

    And share the .master files? Can you post an example, please?


    >>>> Probably what would make the most sense would be to come up with a folder naming pattern for the projects you integrate - and then have your controllers use that when resolving view files from controllers.

    Yes, I thought about that. It is no problem to create /Forum, /News, /Events etc. folders and also use them in url patterns, whereas Forum, News, Events etc. should be different MVC projects.

  • That's it! I am completely sold on this MVC stuff. It just seems more light weight. I actually feel like I could build my ASP.NET faster now.

  • This is actually unrelated to the content itself. It's actually about the font that you are using in Visual Studio. These screenshots look great and I'm a little tired of Courier New. While it looks like you are using Lucida, I can't quite get my Visual Studio to look like yours.

  • Hello Scott,
    I'm building a small app using this mvc framework. Nothing complicated but came across some security issues.
    I managed to fix forms authentication with mvc but my question is about authorization. Actual model doesn't seem to be working as I though it would.
    I can't apply rules for all actions of particular controller using only one location entry (it only applies for controller's index action).
    I found some resources about PrincipalPermissionAttribute and OnPreAction method but I don't like hardcoding authorization rules.
    How it's going to look like? Are You planing to give us nice web.config section something like this:






    or it's up to us build our own solutions?

    Regards

  • Hi Scott,
    I don't know whether its too early to ask this kind of a question :).
    In Monorail, there's a concept of DataBinding which makes a set of related values in a form to be posted to the action method as a single composite object. So in the corresponding action method for the post, we have to have only one parameter instead of one for each form field.
    Are you planning to implement something like that in ASP.NET MVC? If you already have it, please let us know how it could be done.

    Thanks,
    Chamith

  • A problem: if a form has a dozen of fields it is not easy to creat the action controller with so many parameters and then do the databinding between the business object and the form.

    Another question: What are changes with existing server controls? How will validation works?

  • Hi Scott, i know this is off topic but i was wondering how you got the global.asax.cs file to sit outside of the app_code directory? Whenever i try to do this i get a compile error.

  • Hi Scott,
    First thing, i`m very glad that microsoft is going right way and making their products more flexible. I took brief look at this, it looks very nice. I looked at source code (reflector : God bless it;) and i wondering about performance... Controler always use reflection to invoke method, it`s no problem if there are 5-10 web queries/sec. but in large scale this could be a bottleneck (maybe yes/maybe no). Maybe there would be palce for some run-time proxy class (Reflector.Emit?) with methods to direct invoke controler methods? What do you think about this? Maybe you could tell us something about mvc`s performance?

    Best regards,

  • Any ideas why I am getting this when I run the sample app?

    Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.

    Source Error:


    Line 25: public Category GetCategoryById(int categoryId)
    Line 26: {
    Line 27: return Categories.First(c => c.CategoryID == categoryId);
    Line 28: }
    Line 29:


    Source File: D:\MvcApplication5\MvcApplication5\Models\NorthwindDataContext.cs Line: 27

  • Hello Scott,

    If you were working with a medium sized database (approximately 500 tables), did not want to put all of your database helper methods into a single file containing a partial DataContext class, and wanted to group your database helper methods by table, would you:
    (1) Create a separate file for each table containing a partial DataContext class (the definition of the partial DataContext class would then be distributed over 501 files)?
    (2) Create a separate file for each table containing DataContext extension methods?
    (3) Solve the problem a different way?

    Many thanks.

  • Hi Scott,
    I'm starting a project on my spare time and I am very tempted to use the MVC framework. I am aware that this is not currently a final release but I am wondering how "safe" it would be for me to use it on a public facing project. There is no investor or client to satisfy so the risk is ultimately my decision.

    Can I just go ahead and start using all that greatness?

    Thanks

  • I am trying to use the Html.CheckBox() extension, but whenever I use the overload CheckBox(string htmlName, string text, bool isChecked), the HTML rendered sets the attribute to whatever I set for the text parameter to the method. E.G. Html.CheckBox("IsTrue", "Check if true...", false) renders this:

    Check if true...

    If I use one of the overloads that sets the value attribute, that is the value returned on the form POST. Is there a working example of using the CheckBox() method that actually works?

  • Hi Scott, had a truly weird problem. I'm developing an app using ASP.Net MVC and this really had me flummoxed. If focus is on a .aspx tab in the IDE when I run the application, ViewData remains null. I need to change focus to some other open file in VS2008 before running, in which case everything works just fine. I've spent _days_ breaking my head over why ViewData was null before figuring out what was happening...
    Would appreciate it it if I could contact you over e-mail for assistance as I'm developing on this full time and need all the help I can get (Only if you have the time to spare, though). You can contact me at my name on this comment _at_ thoughtworks.com

    Thanks so much.

  • Hi Scot
    How to handle within one view more than one action? I think this is common scenario when on page you have more than one action eg. Save, Cancel, Delete???

  • In the controller I will have my business logic. So for a bigger application, I want to have all my BizLogic in a seperate assembly. I tried to do that, but then my views don't find the controller. Is it possible to put them in a different assembly and if yes, how do I have to reference them?
    Thanks, Rainer

  • Hi Scott,

    I was wondering how cascading drop down lists would work?

    Thanks

  • Hi Scott,
    I have a Person class and an inherited Employee class. I need a view for both. What is the best practice to achieve that?
    Thanks, Rainer

  • Hi, first of all, MVC looks great, i know the design pattern, but i never known how to use it with asp.net.

    I have a question:
    ¿how do you map the categoryname and the suppliername in the Html.Select? ¿what if i want to
    map another property?
    Example:
    my Category class have { Id, Name, OtherName }, and when the Html.Select generates the , i want to have OtherName
    ¿is that possible? i don't saw the explicit mapping in your example.

    Thanks, keep working, you have a lot of followers, this is a good framework.

  • Why can a user access the real URLs, like .../Views/Home/About.aspx ?

    Thanks, Rainer

Comments have been disabled for this content.