ASP.NET MVC Preview 5 and Form Posting Scenarios

This past Thursday the ASP.NET MVC feature team published a new "Preview 5" release of the ASP.NET MVC framework.  You can download the new release here.  This "Preview 5" release works with both .NET 3.5 and the recently released .NET 3.5 SP1.  It can also now be used with both Visual Studio 2008 as well as (the free) Visual Web Developer 2008 Express SP1 edition (which now supports both class library and web application projects).

Preview 5 includes a bunch of new features and refinements (these build on the additions in "Preview 4").  You can read detailed "Preview 5" release notes that cover changes/additions here.  In this blog post I'm going to cover one of the biggest areas of focus with this release: form posting scenarios.  You can download a completed version of the application I'll build below here.

Basic Form Post with a Web MVC Pattern

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

 

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

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

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

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

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

Form Post Improvements with Preview 5

The above code works with the previous "Preview 4" release, and continues to work fine with "Preview 5".  The "Preview 5" release, though, adds several additional features that will allow us to make this scenario even better. 

These new features include:

  • The ability to publish a single action URL and dispatch it differently depending on the HTTP Verb
  • Model Binders that allow rich parameter objects to be constructed from form input values and passed to action methods
  • Helper methods that enable incoming form input values to be mapped to existing model object instances within action methods
  • Improved support for handling input and validation errors (for example: automatically highlighting bad fields and preserving end-user entered form values when the form is redisplayed to the user)

I'll use the remainder of this blog post to drill into each of these scenarios.

[AcceptVerbs] and [ActionName] attributes

In our sample above we implemented our product add scenario across two action methods: "Create" and "Save".  One motivation for partitioning the implementation like this is that it makes our Controller code cleaner and easier to read.

The downside to using two actions in this scenario, though, is that we end up publishing two URLs from our site: "/Products/Create" and "/Products/Save".  This gets problematic in scenarios where we need to redisplay the HTML form because of an input error - since the URL of the redisplayed form in the error scenario will end up being "/Products/Save" instead of "/Products/Create" (because "Save" that was the URL the form was posted to).  If an end-user adds this redisplayed page to their browser favorites, or copy/pastes the URL and emails it to a friend, they will end up saving the wrong URL - and will likely have an error when they try and access it later.  Publishing two URLs can also cause problems with some search engines if your site is crawled and they attempt to automatically traverse your action attributes.

One way to work around these issues is to publish a single "/Products/Create" URL, and then have different server logic depending on whether it is a GET or POST request.  One common approach used to-do this with other web MVC frameworks is to simply have a giant if/else statement within the action method and branch accordingly:

The downside with the above approach, though, is that it can make the action implementation harder to read, as well as harder to test. 

ASP.NET MVC "Preview 5" now offers a better option to handle this scenario.  You can create overloaded implementations of action methods, and use a new [AcceptVerbs] attribute to have ASP.NET MVC filter how they are dispatched.  For example, below we can declare two Create action methods - one that will be called in GET scenarios, and one that will be called in POST scenarios:

This approach avoids the need for giant "if/else" statement within your action methods, and enables a cleaner structuring of your action logic.  It also eliminates the need to mock the Request object in order to test these two different scenarios.

You can also optionally now use a new [ActionName] attribute to allow the method name implementation on your controller class to be different than that from the published URL.  For example, if rather than having two overloaded Create methods in your controller you instead wanted to have the POST method be named "Save", you could apply the [ActionName] attribute to it like so:

Above we have the same controller method signature (Create and Save) that we had in our initial form post sample.  The difference, though, is that we are now publishing a single URL (/Products/Create) and are automatically varying the handling based on the incoming HTTP verb (and so are browser favorites and search engine friendly).

Model Binders

In our sample above the signature of the Controller action method that handles the form-post takes a String and a Decimal as method arguments.  The action method then creates a new Product object, assigns these input values to it, and then attempts to insert it into the database:

One of the new capabilities in "Preview 5" that can make this scenario cleaner is its "Model Binder" support.  Model Binders provide a way for complex types to be de-serialized from the incoming HTTP input, and passed to a Controller action method as arguments.  They also provide support for handling input exceptions, and make it easier to redisplay forms when errors occur (without requiring the end-user to have to re-enter all their data again - more on this later in this blog post). 

For example, using the model binder support we could re-factor the above action method to instead take a Product object as an argument like so:

This makes the code a little more terse and clean.  It also allows us to avoid having repetitive form-parsing code scattered across multiple controllers/actions (allowing us to maintain the DRY principle: "don't repeat yourself").

Registering Model Binders

Model Binders in ASP.NET MVC are classes that implement the IModelBinder interface, and can be used to help manage the binding of types to input parameters.  A model binder can be written to work against a specific object type, or can alternatively be used to handle a broad range of types. The IModelBinder interface allows you to unit test binders independent of the web-server or any specific controller implementation.

Model Binders can be registered at 4 different levels within an ASP.NET MVC application, which enables a great deal of flexibility in how you use them: 

1) ASP.NET MVC first looks for the presence of a model binder declared as a parameter attribute on an action method.  For example, we could indicate that we wanted to use a hypothetical "Bind" binder by annotating our product parameter using an attribute like below (note how we are indicating that only two properties should be bound using a parameter on the attribute):

Note: "Preview 5" doesn't have a built-in [Bind] attribute like above just yet (although we are considering adding it as a built-in feature of ASP.NET MVC in the future).  However all of the framework infrastructure necessary to implement a [Bind] attribute like above is now implemented in preview 5. The open source MVCContrib project also has a DataBind attribute like above that you can use today.

2) If no binder attribute is present on the action parameter, ASP.NET MVC then looks for the presence of a binder registered as an attribute on the type of the parameter being passed to the action method.  For example, we could register an explicit "ProductBinder" binder for our LINQ to SQL "Product" object by adding code like below to our Product partial class:

3) ASP.NET MVC also supports the ability to register binders at application startup using the ModelBinders.Binders collection.  This is useful when you want to use a type written by a third party (that you can't annotate) or if you don't want to add a binder attribute annotation on your model object directly.  The below code demonstrates how to register two type-specific binders at application startup in your global.asax:

4) In addition to registering type-specific global binders, you can use the ModelBinders.DefaultBinder property to register a default binder that will be used when a type-specific binder isn't found.  Included in the MVCFutures assembly (which is currently referenced by default with the mvc preview builds) is a ComplexModelBinder implementation that uses reflection to set properties based on incoming form post names/values.  You could register it to be used as the fallback for all complex types passed as Controller action arguments using the code below:

Note: the MVC team plans to tweak the IModelBinder interface further for the next drop (they recently discovered a few scenarios that necessitate a few changes).  So if you build a custom model binder with preview 5 expect to have to make a few tweaks when the next drop comes out (probably nothing too major - but just a heads up that we know a few arguments will change on its methods).

UpdateModel and TryUpdateModel Methods

The ModelBinder support above is great for scenarios where you want to instantiate new objects and pass them in as arguments to a controller action method.  There are also scenarios, though, when you want to be able to bind input values to existing object instances that you own retrieving/creating yourself within the action method.  For example, when enabling an edit scenario for an existing product in the database, you might want to use an ORM to retrieve an existing product instance from the database first within your action method, then bind the new input values to the retrieved product instance, and then save the changes back to the database.

"Preview 5" adds two new methods on the Controller base class to help enable this - UpdateModel() and TryUpdateModel().  Both allow you to pass in an existing object instance as the first argument, and then as a second argument you pass in a security white-list of properties you want to update on them using the form post values.  For example, below I'm retrieving a Product object using LINQ to SQL, and then using the UpdateModel method to update the product's name and price properties with form data.

The UpdateModel methods will attempt to update all of the properties you list (even if there is an error on an early one in the list).  If it encounters an error for a property (for example: you entered bogus string data for a UnitPrice property which is of type Decimal), it will store the exception object raised as well the original form posted value in a new "ModelState" collection added with "Preview 5".  We'll cover this new ModelState collection in a little bit - but in a nutshell it provides an easy way for us to redisplay forms with the user-entered values automatically populated for them to fix when there is an error.

After attempting to update all of the indicated properties, the UpdateModel method will raise an exception if any of them failed.  The TryUpdateModel method works the same way - except that instead of raising an exception it will return a boolean true/false value which indicates whether there were any errors.  You can choose whichever method works best with your error handling preferences.

Product Edit Example

To see an example of using the UpdateModel method in use, let's implement a simple product editing form.  We'll use a URL format of /Products/Edit/{ProductId} to indicate which product we want to edit.  For example, below the URL is /Products/Edit/4 - which means we are going to edit the product whose ProductId is 4:

Users can change the product name or unit price, and then click the Save button.  When they do our post action method will update the database and then show the user a "Product Updated!" message if it was successful:

We can implement the above functionality using the two Controller actions methods below.  Notice how we are using the [AcceptVerbs] attribute to differentiate the Edit action that displays the initial form, and the one that handles the form post submission:

Our POST action method above uses LINQ to SQL to retrieve an instance of the product object we are editing from the database, then uses UpdateModel to attempt to update the product's ProductName and UnitPrice values using the form post values.  It then calls SubmitChanges() on the LINQ to SQL datacontext to save the updates back to the database.  If that was successful, we then store a success message string in the TempData collection and redirect the user back to the GET action method using a client-side redirect (which will cause the newly saved product to be redisplayed - along with our TempData message string indicating it was updated).  If there is an error either with the form posted values, or with updating the database, an exception will be raised and caught in our catch block - and we will redisplay the form view again to the user for them to fix.

You might wonder - what is up with this redirect when we are successful?  Why not just redisplay the form again and show the success message?  The reason for the client-redirect is to ensure that if the user hits the refresh button after successfully pressing the save button, they don't resubmit the form again and get hit with a browser prompt like this:

Doing the redirect back to the GET version of the action method ensures that a user hitting refresh will simply reload the page again and not post back.  This approach is called the "Post/Redirect/Get" (aka PRG) pattern.  Tim Barcz has a nice article here that talks about this more with ASP.NET MVC.

The above two controller action methods are all we need to implement in order to handle editing and updating a Product object.  Below is the "Edit" view to go with the above Controller:

Useful Tip: In the past once you started added parameters to URLs (for example: /Products/Edit/4) you had to write code in your view to update the form's action attribute to include the parameters in the post URL.  "Preview 5" includes a Html.Form() helper method that can make this easier.  Html.Form() has many overloaded versions that allow you to specify a variety of parameter options.  A new overloaded Html.Form() method that takes with no parameters has been added that will now output the same URL as the current request. 

For example, if the incoming URL to the Controller that rendered the above view was "/Products/Edit/5", calling Html.Form() like above would automatically output <form action="/Products/Edit/5" method="post"> as the markup output.  If the incoming URL to the Controller that rendered the above view was "/Products/Edit/55", calling Html.Form() like above would automatically output <form action="/Products/Edit/55" method="post"> as the markup output.  This provides a nifty way to avoid having to write any custom code yourself to construct the URL or indicate parameters.

Unit Testing and UpdateModel

In this week's Preview 5 drop the UpdateModel methods always work against the Request object's Form post collection to retrieve values.  This means that to test the above form post action method you'd need to mock the request object in your unit test. 

With the next MVC drop we'll also add an overloaded UpdateModel method that allows you to pass in your own collection of values to use instead.  For example, we would be able to use the new FormCollection type in preview 5 (which has a ModelBuilder that automatically populates it with all form post values) and pass it to the UpdateModel method as an argument like so:

Using an approach like above will allow us to unit test our form-post scenario without having to use any mocking. Below is an example unit test we could write that tests that a POST scenario successfully updates with new values and redirects back to the GET version of our action method.  Notice that we do not need to mock anything (nor do we have to rely on any special helper methods) in order to unit test all the functionality in our controller:

Handling Error Scenarios - Redisplaying Forms with Error Messages

One of the important things to take care of when handling form post scenarios are error conditions.  These includes cases where an end-user posts incorrect input (for example: a string instead of a number for a Decimal unit-price), as well as cases where the input format is valid, but the business rules behind the application disallow something from being created/updated/saved (for example: making a new order for a discontinued product).

If a user makes a mistake when filling out a form, the form should be redisplayed with informative error messages that guide them towards fixing it.  The form should also preserve the input data the user originally entered - so that they don't have to refill this manually.  This process should repeat as many times as necessary until the form successfully completes.

Basic Form Entry Error Handling and Input Validation with ASP.NET MVC

In our product edit sample above we haven't written much error handling code in either our Controller or our View.  Our Edit post action simply wraps a try/catch error handling block around the UpdateModel() input mapping call, as well as the database save SubmitChanges() call.  If an error occurs, the controller saves an output message in the TempData collection, and then returns our edit view to be redisplayed:

With earlier preview releases of ASP.NET MVC the above code wouldn't be enough to deliver a good end-user experience (since it wouldn't highlight the problem, nor preserve user input if there was an error).

However, with "Preview 5" you'll find that you now get a decent end-user error experience out of the box with just the above code.  Specifically, you'll find that when our edit view is redisplayed because of an input error it now highlights all input controls that have problems, and preserves their input for us to fix:

How, you might ask, did the Unit Price textbox highlight itself in red and know to output the originally entered user value?

"Preview 5" introduces a new "ModelState" collection that is passed as part of the "ViewData" sent from the Controller to the View when it renders.  The ModelState collection provides a way for Controllers to indicate that an error exists with a model object or model property being passed to the View, and allows a human friendly error message to be specified that describes the issue, as well as the original value entered by the end-user.

Developers can explicitly write code to add items into the ModelState collection within their Controller actions.  ASP.NET MVC's ModelBinders and UpdateModel() helper methods also automatically populate this collection by default when they encounter input errors.  Because we were using the UpdateModel() helper method in our Edit action above, when it failed in its attempt to map the UnitPrice TextBox's "gfgff23.02" input to the Product.UnitPrice property (which is of type Decimal) it automatically added an entry to the ModelState collection.

Html helper methods inside the View by default now check the ModelState collection when rendering output.  If an error for an item they are rendering exists, they will now render the originally entered user value as well as a CSS error class to the HTML input element.  For example, for our "Edit" View above we are using the Html.TextBox() helper method to render the UnitPrice of our Product object:

When the view was rendered during the error scenario above the Html.TextBox() method checked the ViewData.ModelState collection to see if there were any issues with the "UnitPrice" property of our Product object, and when it saw that there was rendered the originally entered user input ("gfgff23.02") and added a css class to the <input type="textbox"/> it output:

You can customize the appearance of the the error css classes to look however you want.  The default CSS error rule for input elements in the stylesheet created in new ASP.NET MVC projects looks like below:

Adding Additional Validation Messages

The built-in HTML form helpers provide basic visual identification of input fields with issues.  Let's now add some more descriptive error messages to the page as well.  To-do this we can use the new Html.ValidationMessage() helper method in "Preview 5".  This method will output the error message in the ModelState collection that is associated with a given Model or Model property.

For example: we could update our view to use the Html.ValidationMessage() helper to the right of the textboxes like so:

Now when the page renders with an error, an error message will be displayed next to the fields with problems:

There is an overloaded version of the Html.ValidationMessage() method that takes a second parameter that allows the view to specify an alternative text to display:

One common use case is to output the * character next to the input fields, and then add the new Html.ValidationSummary() helper method (new in "Preview 5") near the top of the page to list all the error messages:

The Html.ValidationSummary() helper method will then render a <ul><li></ul> list of all the error messages our ModelState collection, and a * and red border will indicate each input element that has a problem:

Note that we haven't had to change our ProductsController class at all to achieve this.

Supporting Business Rules Validation

Supporting input validation scenarios like above is useful, but rarely sufficient for most applications.  In most scenarios you also want to be able to enforce business rules, and have your application UI cleanly integrate with them.

ASP.NET MVC supports any data layer abstraction (both ORM and non-ORM based), and allows you to structure your domain model, as well as associated rules/constraints, however you want.  Capabilities like Model Binders, the UpdateModel helper method, and all of the error display and validation message support are explicitly designed so that you can use whatever preferred data access story you want within your MVC applications (including LINQ to SQL, LINQ to Entities, NHibernate, SubSonic, CSLA.NET, LLBLGen Pro, WilsonORMapper, DataSets, ActiveRecord, and any other).

Adding Business Rules to a LINQ to SQL Entity

In the sample above I've been using LINQ to SQL to define my Product entity and perform my data access.  So far, the only level of domain rules/validation that I am using on my Product entity are those inferred by LINQ to SQL from the SQL Server metadata (nulls, data type and length, etc).  This will catch scenarios like above (where we are trying to assign bogus input to a Decimal).  However, they won't be able to model business issues that can't be easily declared using SQL metadata.  For example: disallowing the reorder level of a product to be greater than zero if it has been discontinued, or disallowing a product to be sold for less than what our supplier price is, etc.  For scenarios like these we need to add code to our model to express and integrate these business rules.

The wrong place to add this business rule logic is in the UI layer of our application.  Adding them there is bad for many reasons.  Among others it will almost certainly lead to duplicated code - since you'll end up copying the rules around from UI to UI and from form to form.  In addition to being time-consuming, there is an excellent chance doing so will lead to bugs when you change your business rule logic, and you forget to update it everywhere. 

A much better place to incorporate these business rules is at your model or domain level.  That way they can be used and applied regardless of what type of UI or form or service works with it.  Changes to the rules can be made once, and picked up everywhere without having to duplicate any logic.

There are several patterns and approaches we could take to integrate richer business rules to the Product model object we've been using above: we could define the rules within the object, or external from the object.  We could use declarative rules, a re-usable rules engine framework, or imperative code.  The key point is that ASP.NET MVC allows us to use any or all of these approaches (there aren't a bunch of features that require you to always do it one way - you instead have the flexibility to reflect them however you want, and the MVC features are extensible enough to integrate with almost anything).

For this blog post I'm going to use a relatively simple rules approach.  First I'm going to define a "RuleViolation" class like below that we can use to capture information about a business rule that is being violated within our model.  This class will expose an ErrorMessage string with details about the error, as well as expose the primary property name and property value associated with it that is causing the violation:

(note: For simplicity sake I'm only going to store only one property - in more complex applications this might instead be a list so that multiple properties could be specified).

I will then define an IRuleEntity interface that has a single method - GetRuleViolations() - which returns back a list of all current business rule violations with that entity:

I can then have my Product class implement this interface.  To keep the sample simple I'm embedding the rule definition and evaluation logic inside the method.  There are better patterns that you can use to enable reusable rules, as well as to handle more complex rules. If this sample grew I'd refactor the method so that the rules and their evaluation where defined elsewhere, but for now to keep this simple we'll just evaluate three business rules below like so:

 

Our application can now query the Product (or any other IRuleEntity) instance to check its current validation status, as well as retrieve back RuleViolation objects that can be used to help present UI that can guide an end-user of the application to help fix them.  It also allows us to easily unit test our business rules independent of the application UI.

For this particular sample I am going to choose to enforce that our Product object is never saved in the database in an invalid state (meaning all RuleViolations must be fixed before the Product object can be saved in the database).  We can do this with LINQ to SQL by adding an OnValidate partial method to the Product partial class.  This method will get called automatically by LINQ to SQL any time database persistence occurs.  Below I'm calling the GetRuleViolations() method we added above, and am raising an exception if there are unresolved errors.  This will abort the transaction and prevent the database from being updated:

And now in addition to having a friendly helper method that allows us to retrieve RuleViolations from a Product, we have enforcement that those RuleViolations must be fixed before our database is ever updated.

Integrating the above Rules into our ASP.NET MVC UI

Once we've implemented our business rules, and exposed our RuleViolations like above, it will be relatively easy to integrate it into our ASP.NET MVC sample.

Because we added the OnValidate partial method to our Product class, calling northwind.SubmitChanges() will raise an exception if there are any business rule validation issues with a Product object that we are trying to save.  This exception will abort any database transactions, and will be caught in our catch block below:

The one extra line of code we'll then add to our error catch block is some logic to call a UpdateModelStateWithViolations() helper method defined below.  This method retrieves a list of all rule violations from an entity, and then updates a ModelState collection with appropriate model errors (including references to the properties on our entity object that caused them):

Once we do this, we can re-run our application.  Now, in addition to seeing input format related error messages, ASP.NET MVC's validation helpers will also display our business rule violations as well. 

For example, we could set the unit price to be less than a $1, and try to set the Reorder level to be -1 (both values are legal from an input format perspective - but both violate our business rules).  When we do this and hit save we'll see the errors show up in our Html.ValidationSummary() list, and the corresponding textboxes will be flagged:

Our business rules can span multiple Product properties.  For example: you might have noticed above that I added a rule that said that the reorder level can't be greater than zero if the product is discontinued:

The only changes we needed to make to our "Edit" view template throughout this entire business rules process has been to add two more Product properties (Reorder and Discontinued) to the file:

Now we can add any number of additional business validation rules we want to our Product entity, and we do not need to update the Edit view nor the ProductsController in order to have our UI support them.

We can also unit-test our model and business rules separately from our Controller and View.  We can unit-test our URL routing separately from our Controller, Views and Models.  And we can unit test our Controller separately from our Views.  All of the scenarios shown in this blog post will support unit testing without requiring any mocking or stubbing to be used.  The end result are applications that are easily testable, and which can support a nice TDD workflow.

Summary

This post has provided a quick look at how form post scenarios work with ASP.NET MVC Preview 5.  Hopefully after reading it you have a better sense of how you handle form and input entry scenarios using a MVC model.  You can download a completed C# version of the application I built above here.  I will post a VB version a little later this week (it is unfortunately 4:30am while I'm typing this and I need to hop on a plane in a few short hours and have not started packing yet).

Important: If you don't like the MVC model or don't find it natural to your style of development, you definitely don't have to use it.  It is a totally optional offering - and does not replace the existing WebForms model.  Both WebForms and MVC will be fully supported and enhanced going forward (the next release of ASP.NET WebForms will add richer URL routing features, better HTML markup/client-side ID/CSS support, and more).  So if after reading the above post you think "hmm - that doesn't feel natural to me", then both don't worry, and don't feel like you should or need to use it (you don't). 

In my next post on MVC I'll cover how to integrate AJAX into your ASP.NET MVC applications. 

Hope this helps,

Scott

189 Comments

  • Hey Scott

    Been checking here every couple of days and happy to see your back and well.

    Another great article as always. I have been teaching myself MVC based on your blog posts. Is there any other resources you would recommend?

    Kind Regards

    Chris

  • Scott, yours posts are like a honey.. And I'm the hungriest bear..

  • Thank you Scott for explaining all the new features of P5.

  • Hope you had a great vacation Scott! This looks like an awesome set of changes :) The HTTP Verbs and the auto binding to entities are very welcome additions IMHO. The approach to validations is almost identical to what I'm working with now (hand rolled).

    On a slight tangent, I have seen most of the features mentioned above in Ruby on Rails (in some form or another). Are there any existing/upcoming ASP.MVC features that can't be found in Rails? Any features that you think are particularly cool? I hope that doesn't come across the wrong way, I'm just interested in the product vision.

    Cheers for the update. I'm really enjoying ASP.NET MVC, and look forward to getting hold of Preview 5 ASAP :)

  • Looks like it's all coming together. The built-in validation is nice and extensible. The action argument binding is great, and I missed it from MonoRail. I can't wait for subcontroller support. Current project is really asking for subcontrollers. Overall, great job everyone!

  • When it will be realesed?

  • Thanks Scott for this detailed post. It's very helpful.

    I'm curious about this whole business of having multiple action method overloads that do totally different things depending on whether they're invoked with a GET or with a POST. You wouldn't abuse method overloads like that in normal C# code (C# method overloads typically achieve the same result, just using different parameters), so why would you use method overloads like that in ASP.NET MVC apps?

    Also, I notice that for this to work, the two overloads need to have different signatures to satisfy the C# compiler, even when for the purposes of your MVC app there may be absolutely no reason to add artificial extra method params to the "POST" overload. A bit messy.

    It's more awkward still if your C# methods are named differently but you fudge them into a single logical action using the [ActionName] attribute, as in your Create()/Save() example. Why deliberately have a naming clash? Why force yourself and colleagues to remember that certain action methods don't really have the same name that Visual Studio thinks they do? Is this really the recommended practise, and if so, what is the benefit of doing this?

    I fully appreciate that Preview 5 still supports the more conventional approach of having different action method names to do different things (e.g., Create() and Save()), and by default action methods have the same name as their C# implementation. Encouraging developers to preserve this simplicity seems hugely preferable at first glance.

    Nice work with the ModelState and model binder stuff though, that looks great!

  • Does the moving of the ActionLink and Form methods that take Expressions to Microsoft.Web.Mvc signify that they'll be removed in the future? Because.. I like those.

  • Curious why you guys departed from the Request.DeserializeTo(...) approach you were using with BindingHelperExtensions.UpdateFrom(...). I liked the convention-over-configuration approach of not having to create a ModelBinder and instead naming my form fields modelname.attribute. Is this still usable?

  • UpdateModel question:

    Many times I have a domain object that I'm using a form to only partially update a few of it's properties.

    ie.
    Let's say I have a Customer object with an Address

    I create a control that handles updating the customer's Address.

    Street1
    Street2
    City, State, PostalCode

    I want to bind just those 5 properties to the Customer's Address object.

    Another senario - I have a Customer object and a form that only updates 2 properties - ie. Name and PhoneNumber. So it's like a 'partial update' - is this possible without much code?

    ie. I would hope to just pass the UpdateModel the Customer object and the two fields and then save it

    public ActionResult SaveCustomer(Customer c)
    {
    UpdateModel(c, new[]{"Name", "TelephoneNumber"});
    }

    possible?

    Thanks

  • Also, I like the focus on RESTful controllers that use the HTTP method to determine what action to fire, but I'm curious why the same thing couldn't be accomplished in the routes using route constraints? Then we wouldn't need the extra ceremony of attributes in the controller. Method overloads are pretty clear with or without specifying the HTTP verb in an attribute. Also, by using routes for specifying HTTP verbs instead of the controller, we could then use REST in a very elegant way similar to Rails, in which GET on /product would go to one action, but POST on /product would go to another.

  • No love for IDataErrorInfo?


  • There still doesn't seem to be a compelling client side validation story short of duplicating validation logic in your javascript library of choice... :(

  • Hope your paternity leave was great...

  • I do see some of the appeal of what you're doing, by the way - I'm just working through the questions at the same time.

  • Hi Scott,

    Great post as usual.

    All this stuff looks really cool, but I've noticed that you've made sure the names of the textboxes match the names of the properties. Same thing for the ValidationMessage helper-function.

    Product.ProductName is put in a textbox called "ProductName". The name passed in the ValidationMessage is also "ProductName".

    Does these things have to match up in order to use the ModelState like you do?
    Or can I have something like: Product.Name and a textbox called "name-of-the-product" and still get all the sweet stuff?

    Sorry if I've missed something obvious in your post (there was a lot of information to process ;)

    - Mads

  • The separate strategies for binding detached and attached models via UpdateForm and IModelBinder respectively, is better, but is still going to be problematic. In practice, what is going to happen is people are going to run into edge cases, and they are going to override each one each time leading to an explosion of these methods/classes that have to be maintained in tandem. ComplexModelBinder still has a ways to go.

    Also, you should consider the way the Spring Web MVC's SimpleFormController handles the two cases (detached and attached). There, you override formBackingObject, which is called before binding occurs. In the 'new' case, you just return an new instance, in the 'edit' case, you load one from the db. This is nice because you are only varying the object loading strategy as opposed to varying both the object loading strategy and the binding strategy. I realize this could be more challenging to implement in a multi action scenario like we have for IController.

    Here's an idea, how about you can create two methods in your icontroller, loadNew() and loadExisting() or something like that. Then, get rid of the UpdateForm, and just use IModelBinder for the param-type binding, but change the GetValue signature so it takes in an object, instead of Type. Before running GetValue, call one of these methods to get the model to pass to GetValue. Then we don't have to vary the binding strategy.

    Also, If you implement recursive binding of collection and there objects, and a way to register type converters for a path (i.e. RegisterTypeConverter('User.Addresses.CreatedDate', new DateTimeConverter()) or whatever, that would be great.

    Thanks!

  • Wow, I love MVC it is just what .NET needs the web developer model for web developers.
    I was driven to .NET back in 1.0 because of the power of XML/XSLT but ASP.NET was never my cup of tea... (I have have never developed Windows App but I have been building websites since 96, so whole one form per page and postbacks just feels strange).
    I would love to see some concepts of using XSLT as templating language for MVC.

  • Hello Scott, thanks for the post.

    I'm currently porting the web application we have from preview 4 to preview 5.

    I was curious about internationalization / localization / globalization, whichever you prefer. I liked asp.net's approach with global and local resources. I know how to access global with the vs-generated designer files, but I'd like to have local resources for certain views and so on. Is there already something with asp.net MVC for that or is that something that is planned for later?

  • By the way, what happened to the CheckBoxBuilder ?

    Not only is it gone, but there is still not a CheckBoxList

    Without the values - retrieving a list by value to determine which is selected is problematic isn't it

  • 太精彩了,学到不少,非常感谢!!
    Great post! I've learned a lot from your blog, Thank you very much!

  • Scott, great post, what a comeback! Thanks!

  • What about page with multiple parts. More and more web pages are rich and offer more than one context.
    From my point of view, making MVC compliant on a page with multiple context ( implies different controller for each context ) an interesting feature will be to get a kind of MVC UpdatePanel that on client side (after load) will send an MVC Get to retrieve its content and allow partial management via MVC Post.
    The more I think on MVC in "real world" the more I fill this feature will be a corner stone for ASP.NET MVC Framework.
    Do you intend to go into this direction?

  • Hi Scott,

    Quick question on "Html.Form()". This is really nice, but what if I want to pass in htmlAttributes for setting things like enctype="multipart/form-data"? With the current method overloads, I have to specify controller name and action name if I want to pass in htmlAttributes. I'd like to be able to do this:

    Html.Form(new { enctype="multipart/form-data" })

    thanks,

    --jeff

  • Wow Scott & the ASP.NET MVC ninja’s… the new binding functionality is a huge improvement in terms of testability. Fantastic! I’m curious how advanced the binding mechanism is, especially with regards to binding associated objects (both singular and collections). Can anyone shed some light? Guess I’m gonna give it a try anyway.

    And as for the validation: hallelujah! What a neat, clean and flexible way to solve this area that usually requires such tedious coding! Brilliant.

    Guys, it’s especially because of your team's efforts that I’m finally starting to gain great confidence in Microsoft’s development routemap. It’s been a while, but now… hoooweee!

    Cheers, Pascal

    BTW, a 10D for only 10.99? Are you kidding me? What’s the URL of that webshop?! Oh darn, it’s in the test code only! ;)

  • Is there a built in HttpVerbs enum that we could use, instead of writing "GET"? Might give some nice code hinting.

    Also very important is that the framework allows for reusable validation logic on the client. There are so many validation tools being developed right now, I believe there's 4 on codeplex already. And the enterpsie library has one as well. Probably not going to happen in the 1.0 version?

  • Scott,

    Can you post a link to your color scheme (settings file).

    :)

  • Thanks, another great post Scott! At last, the validation issue is nicely covered and handled :).

    Although i would like to point out one little problem (as it seems too me):

    Don't you think that UpdateModel(..., new [] { "...", "..." }) is a little too untyped for .NET 3.5 :)? This will again raise issues with refactoring and renaming of model classes. Wasn't that one of the goals of strong typed linq queries and of it's strongest benefits. Why can't we use lambdas, as everywhere else?

    I think we really need something like UpdateModel(..., new [] { p => p.UserName, p => p.LastName } ).

    p.s: and again, can't we also have some overload like: Html.TextBox(viewData => viewData.Product.FirstName) ? For strongly typed view data scenarios?

  • Nice article.
    I am very pleased to see that MVC project is progressing rapidly.

  • thank you Scott, welcome back, could you please post more about Linq to Entities/Linq to SQL on a n-Tier scenario, looks like is not possible to work like that, how is the better way to work with "Linq to.."? and about MVC is there a way to approach something with Silverlight? or would be MVP?

  • So I'm still trying to follow the direction of ASP.Net MVC. What is the mandate? I was assuming it was just a pattern to enforce logical layer seperation but all I see is something Muddying up the HTML and making it harder for my designers. In Addition, it seems quite apparent that the design decisions aren't based on giving an end user the most responsive UI (Case in point, a post with a redirect ala the 1990's). Where is this thing headed?

  • Slightly off topic... I'm wondering, now that ASP.NET MVC is relying more and more upon Attributes, what is the strategy to keep IronPython and IronRuby compatible? I can almost envision Attributes being auto-generated as python decorators for IronPython, but it's difficult to imagine something that would work for both languages (without adding new language features) and at the DLR level as well. It would be interesting to hear if this is on your radar and what is being considered.

  • Hi Edward,

    >>>>>> Slightly off topic... I'm wondering, now that ASP.NET MVC is relying more and more upon Attributes, what is the strategy to keep IronPython and IronRuby compatible? I can almost envision Attributes being auto-generated as python decorators for IronPython, but it's difficult to imagine something that would work for both languages (without adding new language features) and at the DLR level as well. It would be interesting to hear if this is on your radar and what is being considered.

    Attributes are our current “registration” mechanism, but if you look closely, you’ll notice we went through great pains to try and remove reflection specific info. For example, action filters no longer have a MethodInfo property.

    In a future MVC build we’ll have runtime registration methods for filters and those can be used by the DLR as well as statically typed languages, which should enable clean integration with dynamic languages.

    Hope this helps,

    Scott

  • Scott
    great post as always. Something not really clear on the binding model. You omitted how to serialize the object and pass it to the MVC. Did I miss something? Could you provide a small sample?

    thanks.

  • I hava a qustion to ask you!
    HTML Code






    Controller Code

    public class ArStatusController : Controller
    {
    public ActionResult Index()
    {
    // Add action logic here
    ViewData["temp"] = DateTime.Now;
    return View("ArStatus");
    }
    public ActionResult Add(string test)
    {
    ViewData["temp"] = DateTime.Now;
    ViewData["test"] = "hello:"+test;
    retutn View("ArStatus");

    }
    }

    then i use RenderAction include the usercontrol

    <%Html.RenderAction(ar => ar.Index()); %>

    first loading the page,i can get the right html code that include usercontrol and aspx's
    then click the "save" button,i can only get the usercontrol html code,
    how i can i do it?thanks

  • Hi Steve,

    >>>>>>> Thanks Scott for this detailed post. It's very helpful. I'm curious about this whole business of having multiple action method overloads that do totally different things depending on whether they're invoked with a GET or with a POST. You wouldn't abuse method overloads like that in normal C# code (C# method overloads typically achieve the same result, just using different parameters), so why would you use method overloads like that in ASP.NET MVC apps?

    >>>>>>> I fully appreciate that Preview 5 still supports the more conventional approach of having different action method names to do different things (e.g., Create() and Save()), and by default action methods have the same name as their C# implementation. Encouraging developers to preserve this simplicity seems hugely preferable at first glance.

    >>>>>>> Nice work with the ModelState and model binder stuff though, that looks great!

    The problem with exposing two different URLs for the initial and then posted actions occurs when you have an error on the post. When you redisplay the form the browser URL will be the /Save one - which means that if a user bookmarks it and comes back later it will blow up. With other MVC frameworks they often do the technique I talked above above, where you have a giant if statement detect whether it is the get or post behavior. The downside is that this makes code a little hard to read IMO. Some Java frameworks append on the HTTP verb name to the method - which is something we considered (and which you can do with a custom route). For for example:

    public ActionResult Create() {
    // todo: get version
    }

    public ActionResult Create_Post() {
    // todo: post version
    }

    We thought that might be a little less elegant though than overloading the method. Of course, if enough people disagree we can always change to use that approach as well.

    Thanks,

    Scott

  • Hi Brennan,

    >>>>>> Does the moving of the ActionLink and Form methods that take Expressions to Microsoft.Web.Mvc signify that they'll be removed in the future? Because.. I like those.

    No - they'll always ship in at least the future assembly. The only signficance is that we aren't 100% positive yet whether they'll be in the officially supported V1 bits (which are guarenteed to be forward compatible in the future and whose API is locked). Things in the future assembly might ship as a separate download from the official 1.0 package - which gives us a little more flexibility to experiment and try things out.

    Hope this helps,

    Scott

  • Hi Joe,

    >>>>>>> Curious why you guys departed from the Request.DeserializeTo(...) approach you were using with BindingHelperExtensions.UpdateFrom(...). I liked the convention-over-configuration approach of not having to create a ModelBinder and instead naming my form fields modelname.attribute. Is this still usable?

    You won't need to create a ModelBinder to work against a standard class with ASP.NET MVC. We are planning to include and "out of the box" modelbinder that works with standard objects, and which uses the modelname.propertyname syntax for mapping incoming parameters.

    The UpdateModel() helper method also uses the modelname.propertyname syntax for mapping paramaters onto an existing instance of an object - and doesn't require you to register any modelbinders.

    The benefit modelbinders do bring, though, is that you now have the flexibility to customize the serialization if you want (whereas before you couldn't). We'll have smart defaults out of the box, though, so you only need to use this customization for truly custom scenarios.

    Hope this helps,

    Scott

  • Hi Steve,

    >>>>>> UpdateModel question: Many times I have a domain object that I'm using a form to only partially update a few of it's properties. ie. Let's say I have a Customer object with an Address. I create a control that handles updating the customer's Address. Street1 Street2 City, State, PostalCode

    >>>>>> I want to bind just those 5 properties to the Customer's Address object. Another senario - I have a Customer object and a form that only updates 2 properties - ie. Name and PhoneNumber. So it's like a 'partial update' - is this possible without much code?

    >>>>>> ie. I would hope to just pass the UpdateModel the Customer object and the two fields and then save it

    >>>>>> public ActionResult SaveCustomer(Customer c)
    >>>>>> {

    >>>>>>> UpdateModel(c, new[]{"Name", "TelephoneNumber"});

    >>>>>> }

    >>>>>>> possible?

    Yep - that is what the UpdateModel method gives you. Just specify the list of properties you do want to update, and it will only update those from the input collection. This gives you the flexibility to-do both of your scenarios above.

    Hope this helps,

    Scott

  • Hi Joe,

    >>>>>>>> Also, I like the focus on RESTful controllers that use the HTTP method to determine what action to fire, but I'm curious why the same thing couldn't be accomplished in the routes using route constraints? Then we wouldn't need the extra ceremony of attributes in the controller. Method overloads are pretty clear with or without specifying the HTTP verb in an attribute. Also, by using routes for specifying HTTP verbs instead of the controller, we could then use REST in a very elegant way similar to Rails, in which GET on /product would go to one action, but POST on /product would go to another.

    You can definitely do different routing based on verbs using route rules in Global.asax. The MVCContrib project has a REST based route registration extension helper that will preconfigure all the REST based URL patterns for you to-do this.

    Hope this helps,

    Scott

  • Hi Daniel,

    >>>>>> No love for IDataErrorInfo?

    For Preview 5 you need to manually transfer your validation messages from your entity to ModelState. We are looking at whether we can support some built-in mechanisms like IDataErrorInfo with a future drop to avoid the need for the helper method I did above. So fingers crossed that might make it in.

    Hope this helps,

    Scott

  • Great post Scott!!! Keep posting..

  • [Although a bit of topic]
    Waiting for Next major release of Silverlight [SL 2 Release candidate1]
    As there is chrome from google We hope that u guys will work with them and on SL build to let the developer convey the client to its usage.

  • Hi Scott,

    I very much like the approach, cannot wait until this stuff is baked.
    One question - is there a way to intercept input validation and specify custom ErrorMessages?
    E.g. in your example where the user enters a random string instead of the decimal number required by the model field you're auto-generating an error message ('.. invalid value ..').
    Is there a way to customize (and localize) this message, without inspecting and changing ModelState explicitely?

    Thanks
    Florian

  • "Both allow you to pass in an existing object instance as the first argument, and then as a second argument you pass in a security white-list of properties you want to update on them using the form post values. "

    Since I'm binding to a presentation specific DTO (rather than domain classes) the old solution seems better, not sure that having to list the properties I'm binding to really adds much.

    "The UpdateModel() helper method also uses the modelname.propertyname syntax for mapping paramaters onto an existing instance of an object - and doesn't require you to register any modelbinders."

    Sure but the the Form is going to have the submit button so when you try to bind it blows up unless you specifically enumerate each property that you want to bind to.

    "By the way, what happened to the CheckBoxBuilder ?
    Not only is it gone, but there is still not a CheckBoxList"

    Yeah and now the arguments on the CheckBox have changed (not even sure what to pass in) which means if you did write your own CheckBoxList extension methods its junk. Can't really work out why check boxes and check box lists are proving so difficult in MVC but they do seem to be a pain point from version to version.

  • I agree with SteveSanderson. The attributed overloads seem to be complication for complication's sake when PRG works well and seems (in my opinion) easier to follow. Sure, you get an extra request from the client - but why should the failure case be any more efficient than the success case? :)

  • Do you plan to provide handling requests asynchronously?

  • Wouldn't this make more sense at the routing level? I'd be interested to know if that was even discussed and if so, why the decision was made to not go that direction.

  • SOURCE CODE PLEASE!

  • In the old model of updating utilizing BindingHelperExtenstions you could update an entire collection of values by specifying the collection name before the property name. For instance, lets say you have the properties:

    Customer.Address.Line1
    Customer.Address.Line2
    Customer.Address.City
    Customer.Address.State
    Customer.Address.Zip

    In the old method you could setup you input fields on the form like so:






    and then in the method on you could do something like so:
    Customer c = new Customer();
    BindingHelperExtensions.UpdateFrom(c.Address, Request.Form, "Address");

    and all of the properties within address would be updated at once. This is especially handy if a customer can have multiple addresses with the same properties.

    Is there anyway of doing this in Preview 5?

    I'd like to be able to update my code to
    UpdateModel(c.Address, new[] { "Address" });

    But this does not seem to update all the property values within Address.

  • Hi Scott,

    I have an action that looks like this

    public ActionResult Save(ContactList myList)

    I also have this class

    public class ContactListBinder : IModelBinder

    That performs some validation and sets the ModelState accordingly.

    Everything works great, but when I unit test the code the GetValue method in the my ContactListBinder is never executed and hence the ModelState is not set correctly.

    My unit test looks like this:

    var results = controller.Save(model);

    Why isn't my binder class executing during unit tests?

    Thanks.
    Emad

  • I will disagree and thing the [AcceptVerb()] attributes are cool. I also think they are useful if you want to use MVC as a stack for Rest services in addition to web sites.

  • +1 for AcceptVerb attribute

  • Hi Mads,

    >>>>>> All this stuff looks really cool, but I've noticed that you've made sure the names of the textboxes match the names of the properties. Same thing for the ValidationMessage helper-function. Product.ProductName is put in a textbox called "ProductName". The name passed in the ValidationMessage is also "ProductName". Does these things have to match up in order to use the ModelState like you do?

    >>>>>> Or can I have something like: Product.Name and a textbox called "name-of-the-product" and still get all the sweet stuff?

    If you want to use the convention based default you'll want to name your textboxes and input elements the same as the properties. You can have the public text string be whatever you want - it is just the actualy "name" attributes in the form that should be the same if you want the binding to work out of the box.

    You *can* register your own Model Binders if you want to-do custom mapping (you can then map things however you want). In general, though, I'd probably recommend using the default convention based model unless there is a very good reason to use different naming though.

    Hope this helps,

    Scott

  • Hi JWheeler,

    >>>>>>> Also, you should consider the way the Spring Web MVC's SimpleFormController handles the two cases (detached and attached). There, you override formBackingObject, which is called before binding occurs. In the 'new' case, you just return an new instance, in the 'edit' case, you load one from the db. This is nice because you are only varying the object loading strategy as opposed to varying both the object loading strategy and the binding strategy. I realize this could be more challenging to implement in a multi action scenario like we have for IController.

    You can build a controller base class like this which provides these overrides. One complication is to come up with a way that does not force the base class to require a specific ORM/DI implementation. Our plan with V1 has been to provide the more general Controller base class that allows anyone to build these prescriptive sub-classes, and then that way we (and others) can add additional more opinionated semantics on top.

    >>>>>>> Here's an idea, how about you can create two methods in your icontroller, loadNew() and loadExisting() or something like that. Then, get rid of the UpdateForm, and just use IModelBinder for the param-type binding, but change the GetValue signature so it takes in an object, instead of Type. Before running GetValue, call one of these methods to get the model to pass to GetValue. Then we don't have to vary the binding strategy.

    I suspect we'll change IModelBinder so that it supports both newing up new instances, as well as updating existing ones. It would then be easy, for example, to build a Model Binder that could pass an object instance into the action method for both new and edit scenarios - which I think conceptually does what you are suggesting above.

    >>>>>>>> Also, If you implement recursive binding of collection and there objects, and a way to register type converters for a path (i.e. RegisterTypeConverter('User.Addresses.CreatedDate', new DateTimeConverter()) or whatever, that would be great.

    Yep - definitely agree on the recursive aspect. I'm pretty sure support for that will be in the final release.

    Thanks,

    Scott

  • Hi Sefyroth,

    >>>>>>>> I was curious about internationalization / localization / globalization, whichever you prefer. I liked asp.net's approach with global and local resources. I know how to access global with the vs-generated designer files, but I'd like to have local resources for certain views and so on. Is there already something with asp.net MVC for that or is that something that is planned for later?

    You should be able to use ASP.NET's existing global and local rsource support with ASP.NET MVC if you use the default View engine out of the box. I believe an InitializeCulture method is also being added to Controller so that you can dynamically switch the culture to use for the request based on the browser settings before your action is invoked.

    Hope this helps,

    Scott

  • Hi Steve,

    >>>>>> By the way, what happened to the CheckBoxBuilder ?

    I'm not actually sure. Have you posted to the MVC forum on http://forums.asp.net about this? Hopefully someone there should have an answer.

    Hope this helps,

    Scott

  • Hi Brice,

    >>>>>>> What about page with multiple parts. More and more web pages are rich and offer more than one context. From my point of view, making MVC compliant on a page with multiple context ( implies different controller for each context ) an interesting feature will be to get a kind of MVC UpdatePanel that on client side (after load) will send an MVC Get to retrieve its content and allow partial management via MVC Post.

    There are a couple of approaches you can use today for this - although I think the documentation/samples for the different ways are a little light right now. I'll see if I can try and put this on the list to look at writing up.

    Thanks,

    Scott

  • Hi Jeff,

    >>>>>> Quick question on "Html.Form()". This is really nice, but what if I want to pass in htmlAttributes for setting things like enctype="multipart/form-data"? With the current method overloads, I have to specify controller name and action name if I want to pass in htmlAttributes. I'd like to be able to do this:

    There are a few additional overloads on several of the helper methods that need to be added for convenience sake. One challange we do have is making sure that the overloads don't get confusing or conflict. Because many of the params are of type string or object you need to be careful not to make them ambiguous. But hopefully after a pass over them we'll get some useful additions.

    Hope this helps,

    Scott

  • Hi Alexandar,

    >>>>>> Don't you think that UpdateModel(..., new [] { "...", "..." }) is a little too untyped for .NET 3.5 :)? This will again raise issues with refactoring and renaming of model classes. Wasn't that one of the goals of strong typed linq queries and of it's strongest benefits. Why can't we use lambdas, as everywhere else?

    >>>>>> I think we really need something like UpdateModel(..., new [] { p => p.UserName, p => p.LastName } ).

    I'll ping the team to see if that might be possible. I *think* syntactically it can be supported. No promises - but I'll pass the suggestion along.

    Thanks,

    Scott

  • Hi Doug,

    >>>>>>> One thing that has been bugging me about many of the MVC samples I've seen is the use of root-absolute URLs in links and forms. For example, ... or .... Maybe it is all in the name of keeping things simple, but it seems to bypass a very important issue. What happens when I need to move my application to a new location on the web server? Those URLs will cause me no end of trouble.

    >>>>>> I would love to see demos that reinforce good practices like using appropriate application-relative URLs. In fact, I would be interested in how this kind of thing is best done with MVC. I assume the Html.* helpers have support for this, but I've never really seen it discussed.

    I'm pretty sure that the Html.ActionLink() and other helpers resolve URLs from the application root if you are basing your application below the site path.

    Thanks,

    Scott

  • Hi Jorge,

    >>>>>> thank you Scott, welcome back, could you please post more about Linq to Entities/Linq to SQL on a n-Tier scenario, looks like is not possible to work like that, how is the better way to work with "Linq to.."? and about MVC is there a way to approach something with Silverlight? or would be MVP?

    I will put it on the list (although it is a somewhat long topic list at the moment!)

    Thanks,

    Scott

  • Hi Emad,

    >>>>>>> I have an action that looks like this

    >>>>>>> public ActionResult Save(ContactList myList)

    >>>>>>> I also have this class

    >>>>>>> public class ContactListBinder : IModelBinder

    >>>>>>> That performs some validation and sets the ModelState accordingly.

    >>>>>>> Everything works great, but when I unit test the code the GetValue method in the my ContactListBinder is never executed and hence the ModelState is not set correctly.

    >>>>>>> My unit test looks like this:

    >>>>>>> var results = controller.Save(model);

    >>>>>>> Why isn't my binder class executing during unit tests?

    When you are calling your action method directly in a unit test the filters and modelbinders won't automatically run (there isn't any way for them to intercept the call when invoked that way). What you can do, though, is add a line of code before your controllr.Save(model) call that invokes the binder explictly, and passes in the controller.ViewState.ModelState property as the ModelStateDictionary to populate. That way when your controller action executes the ModelState dictionary will be setup for it.

    Hope this helps,

    Scott

  • Hi Andrew,

    >>>>>> SOURCE CODE PLEASE!

    The ASP.NET MVC Preview 5 source code can now be downloaded on this page: http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16775

    You can download the source code for the samples i built in this blog post here: http://www.scottgu.com/blogposts/mvcpreview5/mvcapplication49.zip

    Hope this helps,

    Scott

  • Hi Tim,

    >>>>>>> In the old model of updating utilizing BindingHelperExtenstions you could update an entire collection of values by specifying the collection name before the property name. For instance, lets say you have the properties:

    >>>>>>> BindingHelperExtensions.UpdateFrom(c.Address, Request.Form, "Address");

    >>>>>>> and all of the properties within address would be updated at once. This is especially handy if a customer can have multiple addresses with the same properties. Is there anyway of doing this in Preview 5?

    Good question - I *think* you can do this:

    UpdateModel(c.Address, Request.Form.AllKeys, "Address");

    And have it work. Send me email if you have problems (scottgu@microsoft.com) and I can drill into it more.

    Thanks,

    Scott

  • Hi Joe,

    >>>>>>> Do you plan to provide handling requests asynchronously?

    Yes - we are planning on support async execution. This probably won't be in the initial V1 release, but V1 is being explictly designed so that we can add it in the follow-up release.

    Hope this helps,

    Scott

  • Hi CMV,

    >>>>>> Wouldn't this make more sense at the routing level? I'd be interested to know if that was even discussed and if so, why the decision was made to not go that direction.

    You can definitely do the action method dispatching by verb at the routing level. That works and is supported today. We did, though, want to come up with a way to also control this at the Controller level - so that you could handle it there as well.

    Hope this helps,

    Scott

  • Hi JDC,

    >>>>>>> I agree with SteveSanderson. The attributed overloads seem to be complication for complication's sake when PRG works well and seems (in my opinion) easier to follow. Sure, you get an extra request from the client - but why should the failure case be any more efficient than the success case? :)

    The problem with error scenarios is that you'd need to save the entity on the server in order to have the information survive a redirect. While you can ceretainly use this pattern just fine with ASP.NET MVC (even with Preview 4), we wanted to make sure you didn't have to store it in session state - since that can complicate scale-out and management.

    Hope this helps,

    Scott

  • Hi Colin,

    >>>>>>>> Since I'm binding to a presentation specific DTO (rather than domain classes) the old solution seems better, not sure that having to list the properties I'm binding to really adds much.

    You can use UpdateModel(myDTO, Request.Form.AllKeys) to bind all form elements without requiring the properties to be explictly listed.

    Note that the reason we went with requiring a whitelist by default was to avoid someone inadvertainly allowing client hackers to manipulate properties that shouldn't have on the entity being binded.

    Hope this helps,

    Scott

  • Hi Florian,

    >>>>>>> I very much like the approach, cannot wait until this stuff is baked. One question - is there a way to intercept input validation and specify custom ErrorMessages?

    >>>>>>> E.g. in your example where the user enters a random string instead of the decimal number required by the model field you're auto-generating an error message ('.. invalid value ..').

    >>>>>>> Is there a way to customize (and localize) this message, without inspecting and changing ModelState explicitely?

    Unfortunately with Preview 5 you need to manipulate the ModelState dictionary directy to enable this (either that or override the ModelBinder behavior to customize your own message).

    Hope this helps,

    Scott

  • "You can use UpdateModel(myDTO, Request.Form.AllKeys) to bind all form elements without requiring the properties to be explictly listed.

    Note that the reason we went with requiring a whitelist by default was to avoid someone inadvertainly allowing client hackers to manipulate properties that shouldn't have on the entity being binded."

    That isn't working for me, perhaps because I'm using the Html.Form and Html.SubmitButton approach and if I pass in Request.Form.AllKeys it tries to bind the submit button.

  • Hi Scott,

    We need to know the final release date for asp.net mvc, so we can plan accordingly to go with it or not.

  • Are there any plan to provide an infrastructure supportting user defined/extended components in the views. Such as the Html.GridView() This really let you reuse the complicate code.

    BTW, I really like to do things by strongly typed and reduce the error of writting String

    e.g: Html.TextBox("Name") => Html.TextBox(x=>x.Name) or UpdateModel(p=>p.Name)

    is it reality? Thanks

  • Hi Scott,
    Great work. A subcontroller infrastructure would be a great addition to the framework.
    Thanks

  • Great post. One worth printing out and reading in depth.

  • Binding Question:
    Let's say I'm updating an address. I get the CompanyId passed to the controller from a hidden form variable.

    Typically then I'm looking up the address by company id - then updating the address from the form.

    I think this is a senario that needs to be covered - because I'd like to be able to do something like this:

    [Transaction]
    public object UpdateAddress(Address address)
    { AddressRepository.Save(address); etc...}

    I'm not sure I understand if this would work correctly or not... ie.

    I use NHibernate to get my address, more like this:
    public object UpdateAddress(string id) //address id
    {
    Address address = AddressDao.GetById(new Guid(id));
    //now map in request form variables, ie. address.Street1 = Request["Street1"];
    AddressDao.Save(address);
    return...
    }

  • I should add - that is how I recall Monorail working - it was really quite seamless. (I don't recall registering 'binders' and such)

  • nice post

  • I've downloaded MVC preview 5 and experimenting with this concept. It looks great, but I have one question about ModelBinding:

    It seems you can only define the Model serialization method on the object itself by overriding ToString, or implementing IFormattable/IConvertible (correct me if I am wrong). I am however in the situation that I am using a Business Object layer in a different assembly and I want to serialize these objects so that I can use ModelBinding. Because they are in a different assembly I can't use partial classes. Is there a workaround for this? A nice solution would be if you could override the serialization on the ModelBinder class itself, then both the serialization and deserialization logic would be in the same place and it would be available to any object you put in it.

    Chris

  • Does mapping to a controller action with a nullable type parameter still work? I've been unable to get it working with a nullable int, but it works fine with a string or an int.

    public ActionResult Test(int? id)

    /SomeController/Test/123 returns null.

    Am I missing something?

  • UpdateModel method requires that the keys be provided. So if I want to update every single property on the instance of the object, I have to specify every key, right? Would it be possible to have UpdateModel overload that does not require any keys to be passed but to instead uses properties as keys and tries to find appropriate form entry. In other words update every property for which I have a form field.

  • I may have missed a comment about this, but I was curious as to why the attributes take string values, and not Enum flags (Post | Get). I like to avoid string with teeth whenever possible, and since verbs aren't going to change much, I don't see the reason for strings.

    Is there a reason for this?

  • Nevermind my previous question on nullable parameters. I answered my own question.

    I had model binding setup using ComplexModelBinder for the default binder, and int? is a complex type... so it was trying to use the binder for it and not working as expected.

    Thanks for the great resource on all things ASP.Net

  • In the 4th screen shot shouldn't the form action be /Products/Save, not /Products/Create? In any case I have loved using ASP.NET MVC and look forward to upgrading.
    --Adam Carasso

  • It's great, I want to see the release version of ASP .NET MVC as soom as possible!

  • It's Great, I want to see the release ASP.NET MVC soon

  • Preview5 brings an excellent addition to the form model.
    But, I will get tired of ever putting try catch in my actions to put the same error catching code there. In order to share the error handling code, i would like to be able to know what "entity" i am editing.

    public Product Product {get; set;}

    [AcceptVerbs("POST")]
    [IsEditing("Product")]
    public object Edit(int id, FormCollection form)
    {

    }

    The controller detects the model based on IsEditing attribute
    1) Before executing the action "databinds" using a ModelBinder the Product property to the form data

    2) After the action I would like some sort of error handling filter that does the error logic:

    TempData[CONST_Message] = MyFilter.CustomFormPostErrorMessage;
    UpdateModelStateWithViolations(MyFilter.Model, MyFilter.ViewData.ModelState);
    return View(MyFilter.Model)


    The advantages would be that my code in the actions is much clearer.

    Is this possible to implement now?





  • Are there any hints about creating customized view components to reuse some html function?

    like ListView, FormView, or something has the same html structure.

  • Can you please explain a more mixed approach between classic ASP.NET Forms and MVC? I want full control over everything in the code of the webform. For example I want to use a quite "normal" ASP.NET Form and when the user presses a Save button, put some data in the ViewData based on what the user has done in the form and then pass this data back to the Controller manually. So, i don't want to use the inline code in ASPX like i see in all the examples, but full programmatic control in form events. I haven't been able to accomplish this.

  • I like the color of your screen shots, especial the code screens!

  • Hi Andrea,

    >>>>>> great post as always. Something not really clear on the binding model. You omitted how to serialize the object and pass it to the MVC. Did I miss something? Could you provide a small sample?

    In my download above I have a sample ModelBinder for a Product class that you can use to see how to-do this.

    Hope this helps,

    Scott

  • Hi Colin,

    >>>>>> That isn't working for me, perhaps because I'm using the Html.Form and Html.SubmitButton approach and if I pass in Request.Form.AllKeys it tries to bind the submit button.

    I think there might be an issue with Preview5 with this - where it fails if the property can't be set. I'll follow up with the team to get this fixed for the next release. Until then, it looks like you might need to explictly list the fields I'm afraid.

    Thanks,

    Scott

  • Hi Atit,

    >>>>>> We need to know the final release date for asp.net mvc, so we can plan accordingly to go with it or not.

    We don't have a final ETA for ASP.NET MVC's RTM release just yet - although we are working to ship it this calendar year.

    It supports production deployments today (and has for several months), so you do have the ability to deploy prior to the final release if you want to.

    Hope this helps,

    Scott

  • Hi MVC User,

    >>>>>> Are there any plan to provide an infrastructure supportting user defined/extended components in the views. Such as the Html.GridView() This really let you reuse the complicate code.

    Yep - you can do this today. You can add additional helper methods on the Html object by using the new extension mechanism available with .NET 3.5. in fact, most of the AJAX helper methods are implemented using this extension method mechanism.

    Hope this helps,

    Scott

  • Hi Steve,

    >>>>>> You could accomplish your NHibernate update using code like this:

    public object UpdateAddress(string id) //address id
    {
    Address address = AddressDao.GetById(new Guid(id));

    UpdateModel(address, new [] { "AddressId", "Street1", "Street2", etc });

    AddressDao.Save(address);

    return...
    }

    If you want the signature to instead be:

    public object UpdateAddress(Address address)

    { AddressRepository.Save(address); etc...}

    You could either use the built-in ComplexBinder model binder if you don't need to retrieve the address entity from the database to pass it in, or alternatively you could register a model binder that knew to retrieve the address object from the database, update its properties, and then pass it into the UpdateAddress action method.

    Hope this helps,

    Scott

  • Hi Goran,

    >>>>>> Thanks for the long and descriptive post. This is a little bit off topic, but I post the comment anyway. You close your post saying you will go into integrate AJAX into ASP.NET MVC apps. You should look into my post on how to use jQuery to ease the Ajax integration with ASP.NET MVC based apps.

    Great article - I actually had already read it and bookmarked it for my next AJAX post. :-)

    One thing to note is that with Preview5 the helper methods on the "Ajax" object are now extension methods - and can be unregistered within the web.config file. This would allow you to replace the helper methods with your own JQuery extension methods.

    Hope this helps,

    Scott

  • Hi Chris,

    >>>>>>>> It seems you can only define the Model serialization method on the object itself by overriding ToString, or implementing IFormattable/IConvertible (correct me if I am wrong). I am however in the situation that I am using a Business Object layer in a different assembly and I want to serialize these objects so that I can use ModelBinding. Because they are in a different assembly I can't use partial classes. Is there a workaround for this? A nice solution would be if you could override the serialization on the ModelBinder class itself, then both the serialization and deserialization logic would be in the same place and it would be available to any object you put in it.

    I pinged the team and got back this response:

    "Model binders are used for deserialization only – they aren’t serializers. There’s an open work item where we’re considering making them also perform serialization, but I’m not hopeful that we’ll get to this. We’ve heard of no real user scenario for why you would want to serialize an object rather than pass around some unique identifying information like an ID or key."

    It would be great to have you post more about this scenario in the MVC forum at: http://forums.asp.net to help them understand the scenario more (and potentially elevate it on the feature list).

    Thanks,

    Scott

  • Hi Mark,

    >>>>>> I had model binding setup using ComplexModelBinder for the default binder, and int? is a complex type... so it was trying to use the binder for it and not working as expected.

    I will follow-up with the team on this. I think the default behavior for int? should be to handle nullable types.

    Thanks,

    Scott

  • Hi Brian,

    >>>>>>> I may have missed a comment about this, but I was curious as to why the attributes take string values, and not Enum flags (Post | Get). I like to avoid string with teeth whenever possible, and since verbs aren't going to change much, I don't see the reason for strings.

    That is something a few people have asked about. I'll ping the team to make sure they hear this feedback, and see whether it might be possible to have it be strongly typed.

    Thanks,

    Scott

  • Hi Areg,

    >>>>>> Also I liked the overload on ValidationMessage() that allows for a custom error message. Can we also get an overload on VaidationSummary() in the form of VaidationSummary(Dictionary)

    This is a good suggestion, I'll forward it along to the team.

    Thanks,

    Scott

  • Hi Adam,

    >>>>>> In the 4th screen shot shouldn't the form action be /Products/Save, not /Products/Create? In any case I have loved using ASP.NET MVC and look forward to upgrading.

    Good catch! I had gone back and updated a few of the screenshots, and probably redid that one after i changed the URL without realizing it.

    Thanks,

    Scott

  • Hi ursuletzu,

    >>>>>> But, I will get tired of ever putting try catch in my actions to put the same error catching code there. In order to share the error handling code, i would like to be able to know what "entity" i am editing.

    The good news is that you can write a custom filter attribute that does this today. The filter mechanism enables you to create something like this that can handle this.

    Thanks,

    Scott

  • Hi Double Player,

    >>>>>> Are there any hints about creating customized view components to reuse some html function?

    You can actually reuse a lot of ASP.NET controls like ListView. You can't do post-back scenarios with them, but they do work fine for read-only scenarios.

    MVC also allows people to add helper methods to the Html object in Views - which enables a good encapsulation model as well.

    Thanks,

    Scott

  • Hi Pepe,

    >>>>>> Hello Scott. I've noticed that the error class does not work with the class you assign to the input element.

    That is a good question - I'm not sure whether that is by design or a bug. Can you post about this in the MVC forum on http://forums.asp.net so that the team can see it and comment?

    Thanks,

    Scott

  • Hi Michel,

    >>>>>> Can you please explain a more mixed approach between classic ASP.NET Forms and MVC? I want full control over everything in the code of the webform. For example I want to use a quite "normal" ASP.NET Form and when the user presses a Save button, put some data in the ViewData based on what the user has done in the form and then pass this data back to the Controller manually. So, i don't want to use the inline code in ASPX like i see in all the examples, but full programmatic control in form events. I haven't been able to accomplish this.

    I will try and do some more posts about this in the future.

    Thanks!

    Scott

  • Hi Mark,

    >>>>>> We are looking at using the MVC framework to standardize our UI development. One question I have... Is there a way to configure navigation ala UIPAB (XML file) rather than the programmatic examples usually demonstrated with .NET MVC?

    Yep - you can do this. A couple of approaches you could take:

    1) Use "named routes" instead of explictly referencing the action/controller directly. You could then write code in your Global.asax to dynamically load named routes from an XML file.

    2) You could create and use your own custom helper methods that drive off of the XML file.

    Hope this helps,

    Scott

  • Hi Blake,

    >>>>>> I have been working off your example and would like to provide some feedback from my experience, maybe even fish out a solution or two.

    Thanks for the suggestions on this. I will forward it to the team and see what they can come up with on this.

    Thanks,

    Scott

  • Hi Scott,

    Any particular reason you didn't catch the specific RuleViolationException (which has the list of issues) in the controller so that you didn't have to re-run the validation?

    Also, a small typo "evaluation where defined elsewhere" -> "evaluation were defined elsewhere".

    Excellent post.

    /Damian

  • Thanks for the update and the article.

  • Hi Scott,

    I am just wondering what happens if I have two different forms posting to two different methods in a controller on the same page, but then add the [AcceptVerbs("POST"), ActionName("Index")] attributes to them. It seems like both methods would be called for the post (or an error would be thrown). Is there a way that you could do function overloading for the actual urls?

    Thanks

  • Funny.

    I'm not sure how you Microsoft folks get these ideas, but your example is exactly what I've been doing in Perl for the last 2 years, converted to C#. Nice to see ASP.Net catching up.



  • Masked input doesn't work lovely ... Try binding a masked input masked on a winform to a money value in SQL SERVER ... with a mask type of ###.## .... The data in SQL Server is 25.00 however it displays it as 250.00 in the inputmask control yes I tried setting the prompt character to 0 ... FIX WHAT YOU HAVE BEFORE INPLEMENTING MORE NONSENSE THAT DOESN'T WORK ! WHY SHOULD I HAVE TO WASTE TIME ON SOMETHING SO SIMPLE... YOU GUYS ARE COMPLETELY INCOMPENTENT.... IF YOU WANT, LOOK AT THE VFP APPLICATION INPUTMASK AND FORMAT WORKED CURRENTLY IN THAT APPLICATION. The only thing rapid about vs 2008 is the rate which you can find bugs freaking pathetic...

  • In the rails MVC also is working is same concepts..

  • I was getting "Please wait while installer finishes determining space" pop-up message with any attempt to install ASP.MVC Preview 5 on my virtual machine (Win Server 2008, VS Professional Edition, SP1). This pop-up never returned. I tried to download msi file again - no difference. Suddenly, without any change on my side, it decided to work.

  • Our web application is written in .NET 2.0 and we are using UIP blocks version 2.0. The application was developed 4 years ago and at that time UIP blocks was the only MVC solution available. How can we migrate to ASP.NET MVC?

  • After seeing ASP.NET MVC and seeing that it it totally different than web forms, I think I've decided that I'm not going to put much more effort into ASP.NET in general. I think Microsoft should focus on Silverlight. The HTML way of doing things is just one hack built upon another. It is inelligant and much more of a hassle than it should be. Long live Silverlight.

  • Could not load type 'System.Web.Routing.StopRoutingHandler' from assembly 'System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

  • Hi Scott,

    I have a question about the ActionVerbs. What happens if you have a web page that contains two different forms? If using the action verbs, than both forms would have the same action url (the url for that webpage) but each form would have a different action. Is there a way to overload Actions?

  • What about a situation where you have multiple products being edited at the same time on the page? Do we need to do the "append a number to make the field names unique" technique? Is there a better way? Asp.net was really nice to create unique ids for us.

    John

  • Scott, at one time you said that your team might investigate a way to disable the client ID / name mangling associated with naming containers (master pages, user controls, etc). Will that ever make it into the framework? It would be EXTREMELY useful if there was an attribute on the container that would allow you to "preserve the ID or name defined in the server-side markup" and NOT prepend the IDs of the containing controls. Of course the default behavior (to preserve backward compatibility) would for this attribute (PreserveClientIds?) to be false.

    I think ASP.NET MVC is a decent alternative, but I think with just one simple change like this, many developers could go back to using Master Pages.

    I know why the ID prefixes are added and how they are very useful in cases where a control may be repeated, but I would love the option of being able to turn off the prefixes explicitly when I (the page designer) knew that the usercontrol (in this example) was only used once.

    Thanks! :)

  • Hi Scott,

    I am having some problems here with the localization of the Html helper. At the Edit.aspx, where we have Html.TextBox("UnitPrice"), it prints the number with a dot separator (18.0000) but I need it to print with a comma separator (18,0000), because of my localization. Is there any workaround?

  • Thanks for providing source code. Re: Mandatory Fields. The UpdateModel method seems copy empty strings over to the database. I would assume that it should try to set a null value. eg if the Product Name is set to blank then it should return a mandatory field error as the Product Name is not nullable in the database and also in the model. Also with mandatory fields, it would be good to have a facility which automatically shows an asterix next to the field indicate that the field was mandatory.

  • Great explanation -- I'm impressed with how fast the releases are moving and how stable the previews have been.
    Question, though: how would you do the edit product example with multiple models. For example, if I have a single form that involves an update to two unrelated models (both models are accessible as children of a common parent model), how would I have a single action to accept the form data and separate out the parameters that are for one model vs the other? A simple example would be a form that let's the user edit company and contact information in a single page where the company info is in one model and the contact info is in another model? Would you pass in the two models or would you only update the contact info and company info objects within the user model (and, obviously, how would you do this)? I'm using the modified LINQ to SQL implementation of PLINQO, in case that matters.

  • Awesome post as always Scott, way to go man!

  • Thanks for another great post, Scott. I'm really excited about the MVC framework and we're putting it to good use where I work. However, we've run into a problem with Preview 5 - and it seems we're not the only ones. There are quite a few posts about it on the web already but I've found no solution/workaround that actually works.

    Whenever I double click a view (not the code-behind), Visual Studio just magically shuts down - boom! In the application log there's an error from the .NET runtime: .NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506).

    I run VS2008 on Win2003, and I do not have any of the power tools installed. Any idea what's causing this?

  • When trying to run your example, I get the following error...

    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

    ...Is there anything I need to do on my end to make your example work? Or is it set up as a project just so we can easily view the code, but not run it? If it matters, I'm using Visual Studio 2008 Version 9.0.30729.1 SP

    Thanks.

  • we don't need that stuff. why must we copy java. say 'no' to MVC, MVP, MCT, MCAT, MOM, MOJO or any other abbreviation that starts with M

  • Has there been any work on the MVC team regarding client-side validation? I'd like to be able to express validation rules in one place and have them work both server-side and client-side - I've seen some blog posts regarding this, but I'd like to see what the MVC team is considering before I make a decision I might regret.

    Thanks,
    Erik

  • When I use UpdateModel and I have a field that takes a DateTime? - if the field is left blank, it passes in an empty string instead of a null

    I would expect it to be a null

    What do you think?

  • Great article !

    But I got stuck on how I should deserialize the object if I have a class of class object.
    e.g.
    public string SerialNo {}
    public string ModelNo {}
    public SalesRecord SalesRecordItem {}
    and SalesRecord would contain:
    public int SalesRecordId{}
    public datetime SalesRecordDate{}

    Does anyone come across similar scenario?

    thx,
    George

  • ASP.NET MVC Preview 5とフォーム送信シナリオ

  • Thanks ScottGu, it helped me alot!

  • Hi Scott.
    Really I need your help. Excuse me if my English is bad
    I need one solution for permission manager in my web application.
    One permission provider with these details:
    Each event in my application can be list in one xml file. This permission implements for each my Entity. Example for customer I have: Add, Edit, Delete, and List.
    I think, I need one xml similar to this structure:








    When my users try fire these events, I need check user's roles and return Boolean value.
    If it's true my user can fire up event and if false he can't.

    Meantime I want Use Membership API and .Net Role Provider for manages these events.
    Have you any solutions for my problem?
    Can you help me? Please reply my email because I think you can say to me one resource leastwise or say to me wait for your answer. Please let me know your opinion.
    Thanks,
    A. Esmram

  • How do I implement an HttpHandler? I wrote a little ImageHandler to create thumbnails, etc.,
    I set the reference in the web.config, but I don't know where to start in the HTML code.

    Here's my web.config HttpHandler section:



    Here's my HTML code I'm attempting:



    It reads like: image.axd/{AlbumId}/{PhotoId}/{Size}

    But I'm not getting an error and I'm not getting an image. I know I'm missing something.

    I even tried setting a route in the Global.asax:

    routes.MapRoute(
    "Image",
    "image.axd/{AlbumId}/{PhotoId}/{Size}");

    Any help would be appreciated.

  • Hello,

    The new AcceptVerbs attribute is a great feature but it throws a warning due to the fact Arrays passed as parameters are not CLS Compliant.

    Do you plan to change it in the future to fix this problem?

  • Hi Scott,
    Great post! I think the MVC framework is developing nicely. Just wanted to request consideration for the addition to support IDataErrorInfo for validation. Providing a consistant approach to enabling re-use of validation logic across various GUI implementations (WPF, Silverlight etc..) would sure help reduce code complexity and improve reuse. Do you have any recommended links to validation patterns?

    Also, are there any plans to support client-side validation before the production release of MVC?

    Keep up the good work,

    Adam.

  • The UpdateModel copies empty strings to the database. If you know how to handle it kindly let me know.
    ganesh.acharya@intelcs.com

  • Hi Scott,

    Nice to see you back..... was eagerly waiting for your posts.
    Have a question regarding Html.ActionLink

    I see that it has been modified from using type arguments to strings. I would like to know how can you call a method on a controller which takes 3-4 parameters. for eg.

    <%=Html.ActionLink("Name", "Show", new {id="1", ??, ??});

    ---Controller Method----
    public void Show(int id, string name, Guid userId)


    Please advise

  • Hi Scott,

    I'm quite pleased by the way you are moving on, because it's very original on the field of MVC frameworks (especially the way you work with parameters - it's much more object-oriented than in most other frameworks)!

    However - when I read about the validation and form system, it seamed to me that it hasn't got enough flexibility in setting of the presentation. For example - what if I want the ValidationSummary to be a table, not a list? Or what if I want the Validation Error CSS class to be named some other way? The way it looks like now I find very similar to WebForms, but that's not the goal. Isn't it? Or am I just mystified?:-)

    And one more thing - is it possible to explicitely set the names of input fields in ModelBinder if they doesn't match with the Model Properties?

    Thanks in advance

    P.S.: Your posts are simply great!:-)

  • Was looking forward to Preview5, then you made a bunch of non-sensical changes that broke Preview4. Thats always appreciated.

  • Why was the ActionName property removed from the ActionExecutingContext in Preview5. It wasn't in the release notes, so it comes as a real surprise. We were using it for some determination of whether controller/action pairs need to be authorized or not. Yet the ActionParameters were left in.
    Was was the reason for it's removal?

  • Hi Damien,

    >>>>>> Any particular reason you didn't catch the specific RuleViolationException (which has the list of issues) in the controller so that you didn't have to re-run the validation?

    I could have done that too. It was late at night (5am ) when I finally posted the article, so my eyes were not the sharpest by the final screenshot. :-)

    Thanks,

    Scott

  • Hi Goran,

    >>>>>> I’m also curious about when the support for Dynamic Data in the MVC is released? I would love to see some scaffolding functionality into this framework soon.

    We are working on dynamic data support for MVC right now, and will have more previews of this availble later this year.

    Hope this helps,

    Scott

  • Hi Joel,

    >>>>>> I am just wondering what happens if I have two different forms posting to two different methods in a controller on the same page, but then add the [AcceptVerbs("POST"), ActionName("Index")] attributes to them. It seems like both methods would be called for the post (or an error would be thrown). Is there a way that you could do function overloading for the actual urls?

    If you have two methods for the same action name that both accept Post then you'll get an error thrown (since it is abiguous).

    We origionally looked at doing method overloading based on parameters, but this ends up getting pretty tricky (especially since since HTML form elements like radiobutton have the sematic of not posting anything when they are not selected). We decided doing it by verb was a cleaner and more consistent method to use.

    Hope this helps,

    Scott

  • Hi Celik,

    >>>>>> If i set compilation debug ="false" in web.config file, my routing does not work very well.

    Have you tried posting about this issue on the forums at: http://forums.asp.net? I think there might be a fix for it there.

    Thanks,

    Scott

  • Hi Geek50,

    >>>>>> Could not load type 'System.Web.Routing.StopRoutingHandler' from assembly 'System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

    Two things to check:

    1) You are using .NET 3.5 or .NET 3.5 SP1 (and not the beta)

    2) Any existing MVC applications you had build with previous previews need their web.config files updated. The release notes for Preview5 describe how to-do this.

    Hope this helps,

    Scott

  • Hi Joel,

    >>>>>> I have a question about the ActionVerbs. What happens if you have a web page that contains two different forms? If using the action verbs, than both forms would have the same action url (the url for that webpage) but each form would have a different action. Is there a way to overload Actions?

    You can have each form post to a different URL (just set the action attribute explictly to the URL you want to post to).

    Hope this helps,

    Scott

  • Hi John,

    >>>>>>> What about a situation where you have multiple products being edited at the same time on the page? Do we need to do the "append a number to make the field names unique" technique? Is there a better way? Asp.net was really nice to create unique ids for us.

    You can have your model binders handle arrays of products if you want, and/or you a different prefix with UpdateModel to load each product separately.

    Hope this helps,

    Scott

  • Hi Eric,

    >>>>>>> Scott, at one time you said that your team might investigate a way to disable the client ID / name mangling associated with naming containers (master pages, user controls, etc). Will that ever make it into the framework? It would be EXTREMELY useful if there was an attribute on the container that would allow you to "preserve the ID or name defined in the server-side markup" and NOT prepend the IDs of the containing controls. Of course the default behavior (to preserve backward compatibility) would for this attribute (PreserveClientIds?) to be false.

    Yes - this will be added with the next release of ASP.NET WebForms (which will ship next year). In addition to ID control, the standard ASP.NET WebForms controls will be updated to be CSS friendly.

    >>>>>> I think ASP.NET MVC is a decent alternative, but I think with just one simple change like this, many developers could go back to using Master Pages. I know why the ID prefixes are added and how they are very useful in cases where a control may be repeated, but I would love the option of being able to turn off the prefixes explicitly when I (the page designer) knew that the usercontrol (in this example) was only used once.

    We are going to update WebForms so that they no longer have this issue. Some people will prefer MVC for other reasons, but we want to make sure it isn't because of this issue.

    Thanks,

    Scott

  • Hi Fred,

    >>>>>>> I am having some problems here with the localization of the Html helper. At the Edit.aspx, where we have Html.TextBox("UnitPrice"), it prints the number with a dot separator (18.0000) but I need it to print with a comma separator (18,0000), because of my localization. Is there any workaround?

    Do you have localization setup within your application? If the culture for the request is set to a non-US language, then I think it should automatically format it with a comma for you.

    Thanks,

    Scott

  • Hi Miguel,

    >>>>>> Thanks for providing source code. Re: Mandatory Fields. The UpdateModel method seems copy empty strings over to the database. I would assume that it should try to set a null value. eg if the Product Name is set to blank then it should return a mandatory field error as the Product Name is not nullable in the database and also in the model. Also with mandatory fields, it would be good to have a facility which automatically shows an asterix next to the field indicate that the field was mandatory.

    That is a good question - i just forwarded this off to the feature team to look at.

    Thanks,

    Scott

  • Hi IsDillard,

    >>>>>> Question, though: how would you do the edit product example with multiple models. For example, if I have a single form that involves an update to two unrelated models (both models are accessible as children of a common parent model), how would I have a single action to accept the form data and separate out the parameters that are for one model vs the other? A simple example would be a form that let's the user edit company and contact information in a single page where the company info is in one model and the contact info is in another model? Would you pass in the two models or would you only update the contact info and company info objects within the user model (and, obviously, how would you do this)? I'm using the modified LINQ to SQL implementation of PLINQO, in case that matters.

    Within your form you could have the multiple models use a prefix for the input element name:




    Within your binders or UpdateModel method you can then prefix which set of form posts you want to populate it with:

    Product product1 = new Product();
    UpdateModel(product, new [] { "Name" }, "Product1");

    You could call this multiple times to populate different model objects.

    Hope this helps,

    Scott

  • Hi Anthony,

    >>>>>> I noticed if I use prefixes for my property names, Address.Line1, my css does not apply properly. I changed the delimiter to a "!" and this worked fine; however the UpdateModel method does work. I suspect this method presumes the prefix delimiter is a "." I would like to use the prefix to avoid any conflicts between classes that have the same property and appear on the same page.

    Can you post a repro of this issue in the MVC forum on http://forums.asp.net?

    Thanks!

    Scott

  • Hi Kevin,

    >>>>>> The example I'll use is a session timeout. Our product sits on top of a third party back end using web services. We send them requests in XML and they respond with XML. If the session has timed out on their end, the XML response includes a block with an error. We could go through the whole application and modify every single actionresult to deal with the time out error and return a view, but I'm wondering if there's a chance the MVC environment will allow for a catch all exception handling again. Or maybe I've just missed something and it's still there in a new form?

    You can create a custom filter that you can apply on each controller that will allow you to catch and custom handle errors within the application. Alternatively, you can use the built-in [HandleError] filter that will do this for you automatically.

    Hope this helps,

    Scott

  • Hi Owwind,

    >>>>>> Thanks for another great post, Scott. I'm really excited about the MVC framework and we're putting it to good use where I work. However, we've run into a problem with Preview 5 - and it seems we're not the only ones. There are quite a few posts about it on the web already but I've found no solution/workaround that actually works. Whenever I double click a view (not the code-behind), Visual Studio just magically shuts down - boom! In the application log there's an error from the .NET runtime: .NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506).

    Can you check on the MVC forum @ http://forums.asp.net on this? I think it is because you have SP1 installed with the PowerCommands add-in (which needs to be updated - the older one has an issue with VS 2008 SP1).

    Thanks,

    Scott

  • Hi Greg,

    >>>>>> A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

    Can you check the web.config file's connection string to make sure it is pointing to a valid database on your system?

    Thanks,

    Scott

  • Hi Labible,

    >>>>> The new AcceptVerbs attribute is a great feature but it throws a warning due to the fact Arrays passed as parameters are not CLS Compliant. Do you plan to change it in the future to fix this problem?

    I think we are considering enabling an enum based approach here (which several people have asked for). I think this would fix this issue as well.

    Hope this helps,

    Scott

  • Hi Adam,

    >>>>>>> Great post! I think the MVC framework is developing nicely. Just wanted to request consideration for the addition to support IDataErrorInfo for validation. Providing a consistant approach to enabling re-use of validation logic across various GUI implementations (WPF, Silverlight etc..) would sure help reduce code complexity and improve reuse. Do you have any recommended links to validation patterns?

    Good news - we are planning on supporting IDataErrorInfo with the next MVC update (which will be the beta).

    >>>>>>> Also, are there any plans to support client-side validation before the production release of MVC?

    We won't have client-side validation built-into MVC V1, but you can definitely use a client-side validation approach with it. We'll have samples that show how to-do this.

    Hope this helps,

    Scott

  • Hi VB,

    >>>>>>>>> Nice to see you back..... was eagerly waiting for your posts. Have a question regarding Html.ActionLink

    >>>>>>>>> I see that it has been modified from using type arguments to strings. I would like to know how can you call a method on a controller which takes 3-4 parameters. for eg.

    >>>>>>>> >>>>>>> ---Controller Method----

    >>>>>>>> public void Show(int id, string name, Guid userId)

    I believe you should be able write:

    <%=Html.ActionLink("Name", "Show", new {id="1", name="Scott", userId="{someguidvalue"} );

    Is that not working?

    Thanks,

    Scott

  • Hi Anderson,

    >>>>>>> I like to see validation application block in action and same concept of PropertyProxyControl in validations helpers. Now, with Preview 5, how to do for integrate VAB with MVC and exists a plan that look specifically for this?

    Good news - Stephen just wrote up an excellent post that covers this: http://weblogs.asp.net/stephenwalther/archive/2008/09/09/asp-net-mvc-tip-42-use-the-validation-application-block.aspx

    Hope this helps,

    Scott

  • Hi Vojtěch Vít,

    >>>>>>> I'm quite pleased by the way you are moving on, because it's very original on the field of MVC frameworks (especially the way you work with parameters - it's much more object-oriented than in most other frameworks)!

    >>>>>>>> However - when I read about the validation and form system, it seamed to me that it hasn't got enough flexibility in setting of the presentation. For example - what if I want the ValidationSummary to be a table, not a list? Or what if I want the Validation Error CSS class to be named some other way? The way it looks like now I find very similar to WebForms, but that's not the goal. Isn't it? Or am I just mystified?:-)

    The actual modelstate error information is exposed off the ViewData.ModelState property which is passed to the view. What this means is that you can write your own for-loop or build your own custom extension to render the errors however you want. So you don't need to use the li/ul list that Html.ValidationSummary() generates - if you want you could create your own helper that renders a table.

    >>>>>>>> And one more thing - is it possible to explicitely set the names of input fields in ModelBinder if they doesn't match with the Model Properties?

    The Model Binders are extensible so that you could do this - although with Preview5 you'd need to write code to enable this. We are working on some updates for the next preview that will make a number of scenarios easier (and not require any custom binder code). This scenario will I think be one that gets easier with this.

    Hope this helps,

    Scott

  • Hi thzero,

    >>>>>>> Why was the ActionName property removed from the ActionExecutingContext in Preview5. It wasn't in the release notes, so it comes as a real surprise. We were using it for some determination of whether controller/action pairs need to be authorized or not. Yet the ActionParameters were left in. Was was the reason for it's removal?

    Here is a forum post that talks about this more: http://forums.asp.net/p/1301069/2538397.aspx#2538397

    Hope this helps,

    Scott

  • Hi Scott,
    I have a question regarding Html.ActionLink. I want to create a link like this:
    Login Link
    I know will create a link, but how can I add '' to the link?
    Thank you.

  • Instead of
    UpdateModel(product, new string[] { "Name", "Price" });

    Why not declare UpdateModel as
    public void UpdateModel(object instance, params string[] args);

    So we can instead write this
    UpdateModel(product, "Name", "Price");

    Unless there is a reason not to do this I think it would be much nicer to write.

  • Sorry about posting this question here, but I have been working on a project with silverlight beta 2 and I am close to finishing it up. I would like to demo this project to our customers, but the first question they are going to ask is when can we have it and the answer depends upon when siliverlight 2 is officially released. It's been a long time you posted a blog on Siliverlight, can you please update us as to what's going on that front. Again sorry for posting this question here.

  • Nice article!!
    I've a question that goes beyond the topic, but could impact the way url should display entity identifier. What about having guid instead of id to reference a product. GUID are less readable but you don't necessarily want a user pocking around from products/Edit/1 to 1000. it get more difficult with guid product/Edit/b98afbde-e435-439b-920e-97d28077e244. What is your thought on that?
    Thanks.

  • Hi, there

    What can I do to present several models in one view?

    Thank you

  • G'day Scott,
    I have posted a quick sample on how to get started with Ajax in ASP.Net MVC Preview 5.
    http://shailensukul.blogspot.com/2008/09/aspnet-mvc-ajax.html
    Hope it helps your readers.

  • How can I add tag to linktext? I want create a link like:
    Login!
    I tried to use <%=Html.ActionLink("Login!","Login","Account")%>, but the tag showed directly not like a html tag.
    Thanks.

  • I have a question, couldnt find a convincing answer anywhere.But is religiously followed as best coding practice..please let me know.
    Why should variable declaration not be made inside Try Block. How does it help memory management.

  • Hi Scott,
    Sometimes i wonder. If microsoft has gone bonkers after Vista, everything i see from microsoft is old wine in new bottle, MVC model has been there for a long long time isn't it, then why there is so much hue and cry about MVC tecnology, Well with due respect to your blogs and I love to see more of them its always an pleasure to read more and knwo more but so many articles about a technology which is of past and is included in new .Net makes me think ... is microsoft goign steve balmer way(ie:shout and talk).... well hope its not that way..

  • Scott, thanks for the reply about planned updates to Web Forms regarding better CSS compatibility!!!

    You are the MAN! ;)

    Seriously, take the rest of the day OFF! If anybody asks, let them know some guy on the internet authorized it.

  • Scott,

    I haven't started using the ASP.NET MVC framework yet, so my question might sound naive, but are you catching the general Exception rather than a specific exception for demonstration purposes? I mean, in case of some unexpected error, don't you want to log the error and take the user to some general error page and log the error? Don't you only want to return the user to the form in case of a validation exception, in production code?

  • Hi Scott,
    Thanks for what you're doing on this site.
    Any ideas when you'll be publishing your promised post on MCV Ajax?

  • Hi Scott,

    In my testing, I've discovered that ModelBinders execute before any IAuthorizationFilters or IActionFilters. I'm curious why this is the case. It seems to me that the ModelBinder should be the last thing to execute immediately prior to the action method being invoked because if a user is not authorized to call the method, I would expect the ModelBinder not to be executed.

    I'm interested to hear your thoughts on this.

    --Jeff

  • All your MVC samples show the MVC applications running in the root directory. How would I go about creating a MVC appliction in a virtual directory? Every time I do, I have problems with the Links, Content and Shared folders. None of it maps correctly. Is there a specific config setting I need to set?

  • i think asp.net MVC is awsome but i got a question.

    why is Controller.UpdateModel marked internal? i would like to build an extension method which updates the model AND checks ruleviolations.

  • I am getting an error building while using Microsoft.Web.Mvc.dll; it says that Microsoft.Web.Mvc is not a strongly named assembly. Appreciate any help I can get. Thanks!

  • Hi Scott,

    I'm pleased to see validation making it into the core. Mine is a simple request for a trivial tweak to the AddModelError method.

    I want some clientside code to set focus on the first invalid element when the page is rendered. I'd use a script to:

    1. Grab the ValidationSummary element. (No problem)
    2. From that, pick up the first child element (i.e. the first rendered error). (Fine)
    3. Collect the id of the invalid input itself. (Ah....)
    4. Set focus on that first invalid element.

    I can code Html.ValidationSummary(new {id="ValidationErrors"}), to allow my script to harvest the ValidationSummary element, but there's no overload to ModelState.AddModelError which allows me to add attributes (e.g. "InvalidId") to the individual errors. So it seems my script has no way to identify the source of an error.

    Any chance of adding an overload to AddModelError?

    Cheers,
    Roy.

  • dude, your blog posts are not printer friendly on Firefox 3.0.... :(

  • Here is a small example of using MVC with ModelBinder and Validation Application Block from Ent Lib:

    http://navin.biz/MvcValidation/

  • Hi Scott,

    >>>>>>> Do you have localization setup within your application? If the culture for the request is set to a non-US language, then I think it should automatically format it with a comma for you.

    Well, I've tried to set the culture of the page Edit.aspx to
    and I also tried setting the globalization at the web.config to:


    but it didn't work. Is there another way to set the "culture for the request to a non-US language".

    Thanks in advance,

    Fred

  • On the IModelBinders, I was wondering if when changing the interface you could consider making the signature of GetValue a bit less noisy? In particular I think it would make testing the binders easier.

    For example rather than passing in the ControllerContext did you think of passing in a custom class that (as well as providing access to the ControllerContext) would provide what you need as easily as possible (including the forms collection).

  • any experiences with ASP.NET MVC and ReportViewer?
    is it at all possible to use the ReportViewer Component inside an ASP.NET MVC application?

    TIA
    Stefan

  • Would this be a good way for generic ModelBinder?

    public class GenericModelBinder : IModelBinder
    {
    private T _localObject;

    public EesModelBinder(T t)
    {
    _localObject = t;
    }

    public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState)
    {
    if (controllerContext == null)
    {
    throw new ArgumentNullException("controllerContext");
    }
    if (modelType != typeof(T))
    {
    throw new ArgumentException("This binder only works with " + typeof(T).ToString() + " models.", "modelType");
    }


    foreach (PropertyInfo pInfo in typeof(T).GetProperties())
    {
    IModelBinder binder = ModelBinders.GetBinder(pInfo.PropertyType);
    object value = binder.GetValue(controllerContext, pInfo.Name, pInfo.PropertyType, modelState);
    if (pInfo.CanWrite)
    pInfo.SetValue(_localObject, value, null);
    }

    return _localObject;
    }
    }

    ModelBinders.Binders[typeof(User)] = new EesModelBinder(new User());

  • Another comment on the model binders, it would be useful if we could registered these with a container (StructureMap, Windsor or whatever). In particular when the model binders have their own dependencies (such as a dependency on an IMapper/IFooRepository).

    Currently I have to use this sort of approach:

    public UserBinder()
    :this(IoC.Resolve())
    {
    }

    Design wise this is less than perfect, really I just want MVC to (indirectly) call out to the container to get my UserBinder (or IModelBinder).

  • For Buttons updating an update panel using AJAX, we receive exception error if we use server.transfer while response.redirect works fine but it's expensive. Is a there a better way to manage page transfer
    Regards
    RS
    http://www.healthsprint.com/

  • I've started a blog series on using Preview 5 to create a RESTful web service, your comments would be gratefully received:

    http://shouldersofgiants.co.uk/blog/

  • How do you validate the values from the form in your Binder. There is a ModelstateDictionary parameter to GetValue Member if IModelBinder, but how should I use this.

    Thanks

Comments have been disabled for this content.