ASP.NET MVC V2 Preview 1 Released

The ASP.NET team just released the first public preview of ASP.NET MVC Version 2.  You can download it here.

Today’s preview works with .NET 3.5 SP1 and VS 2008, and can be installed side-by-side on the same machine as ASP.NET MVC 1.0 (meaning they don’t conflict and your existing ASP.NET MVC 1.0 projects will not be impacted if you install it).  If you have both ASP.NET MVC 1.0 and ASP.NET MVC 2.0 installed you’ll see two ASP.NET MVC project templates within Visual Studio 2008’s “New Project” dialog:

The release notes that come with the ASP.NET MVC 2 Preview release detail how to upgrade existing ASP.NET MVC 1.0 projects to use V2 if you’d like to migrate them forward to take advantage of the new features.

New Features

ASP.NET MVC V2 will include a bunch of new capabilities and features (some of these have already been called out on the ASP.NET MVC roadmap page).  Today’s “Preview 1” release contains a first look at some of the new features.  Many more features will show up in future preview builds.  The Preview 1 bits are still relatively early - the team is releasing today’s build to start receiving and incorporating feedback. 

Below are some quick details about some of the new Preview 1 capabilities:

Areas Support

ASP.NET MVC 2 includes support for a new feature called “areas” that allow you to more easily partition and group functionality across an MVC application.

Areas provide a means of grouping controllers and views to allow building subsections of a large application in relative isolation to other sections. Each area can be implemented as a separate ASP.NET MVC project which can then be referenced by the main application. This helps manage the complexity when building a large application and facilitates multiple teams working together on a single application together.

Below is a screen-shot that shows a single solution that has three projects.  One of the projects is named “CompanySite” and includes the core site content, layout and controllers and views. There are then two separate “Area” projects - “Blogs” and “Forums”.  These projects implement the functionality that exists under the /Blogs and /Forums URL sections of the site – and encapsulate all of the routing rules, controllers and views implementing these sections:

The Preview 1 release includes the first part of the areas feature implementation.  It doesn’t include any tool support yet (right now you need to manually add a build task to create an area project and set it up).  Future preview releases will include tooling support, and expand and refine the feature-set further.

DataAnnotation Validation Support

ASP.NET MVC 2 now includes built-in support for the DataAnnotation validation support that first shipped with .NET 3.5 SP1 – and which is used with ASP.NET Dynamic Data and .NET RIA Services.  DataAnnotations provides an easy way to declaratively add validation rules to Model and ViewModel classes within an application, and have automatic binding and UI helper validation support within ASP.NET MVC.

To see this feature in action, we can create a new “Customer” ViewModel class like below that has five properties on it (implemented using the C# automatic property feature).

We can then decorate the properties with appropriate validation rules using the DataAnnotation attributes implemented within the System.ComponentModel.DataAnnotations namespace.  The code below uses 4 different built-in validation rules – [Required], [StringLength], [Range], and [RegularExpression].  The namespace also includes a base class (ValidationAttribute) that you can subclass to create your own custom validation attributes.

We can then create a CustomersController class that has two Create action methods on it.  The first Create action method handles HTTP GET requests to the “/Customers/Create” URL, and renders a view template based on an empty Customer object.  The second Create action method handles HTTP POST requests to the same URL (and takes a Customer object as a method parameter).  It checks if there are any model binding errors to the input submitted, and if there are errors it redisplays the view template using the already entered data.  If there are no errors it displays a success view to the user:

Finally, we can right-click within either of the Create action methods above, choose the “Add View” context menu command, and automatically “scaffold” a “create” view template that is based on the Customer object.  When we do this the generated scaffolded view template will contain the below HTML <form> for our Customer:

And now when we request the “/Customers/Create” URL in our browser we’ll get an initial empty form like below:

If we enter invalid input and perform a post to the server, the ASP.NET MVC 2 model binder will detect that there are DataAnnotations attributes on our Customer class, and automatically validate the posted form input using them.  If there are errors our controller action method redisplays the form – which will cause the appropriate validation error messages to be rendered to the user like below.  Note how the validation property error message strings we specified using the DataAnnotation attributes are displayed to the user by the Html.Validation helper methods.  No extra code is required to enable this.

The above form will redisplay with error messages each time the user enters invalid input and attempts to perform a form post.

In a future ASP.NET MVC 2 preview we are planning to ship the jQuery Validation plugin as part of the default project template, and add support for the automatic client-side JavaScript enforcement of DataAnnotation validation rules as well.  This will enable developers to easily add validation rules in one place on either a Model or ViewModel object, and have them be enforced both client and server-side everywhere it is used within the application.

If you do not wish to annotate your model or viewmodel classes directly, you can alternatively create a “buddy class” that accompanies your model class and encapsulates the DataAnnotaton rules separately.  This capability is also useful for scenarios where VS is code-generating/updating the properties on a class directly and you cannot easily add attributes to the generated code (for example: classes generated by the LINQ to SQL or LINQ to Entities designers). 

In addition to providing built-in support for DataAnnotations, the DefaultModelBinder class in ASP.NET MVC V2 now has new virtual methods that can be overridden to easily integrate other validation frameworks as well (for example: Castle Validator, EntLib Validation, etc).  The validation UI helper methods in ASP.NET MVC are designed to support any type of validation framework (they have no direct knowledge of DataAnnotations).

Strongly Typed UI Helpers

ASP.NET MVC V2 includes new HTML UI helpers that enable you to use strong-typed lambda expressions when referencing the view template’s model object.  This enables better compile-time checking of views (so that bugs can be found at build-time as opposed to runtime), and also enables better code intellisense support within view templates.

You can see an example of the better intellisense in action below – notice how I am getting a full listing of the customer model object’s properties when using the new Html.EditorFor() helper method:

Preview 1 has built-in support for new Html.EditorFor(), Html.LabelFor(), and Html.DisplayFor() helpers.  An updated MVC futures assembly that we are shipping this week adds additional Html.TextBoxFor(), Html.TextAreaFor(), Html.DropDownListFor(), Html.HiddenFor(), and Html.ValidationMessageFor() helper methods as well (overtime these will move into the core ASP.NET MVC 2 assembly too).

Below you can see an updated version of the “create” view template for our customer creation scenario.  Notice how instead of using string expressions to reference the customer object we are instead using strongly-typed lambda expressions with the UI helpers.  We can get full intellisense and compile-time checking with all of them:

The Html.LabelFor() helper method above generates <label for="Name">Name:</label> HTML markup.

The Html.EditorFor() helper method can be used for any datatype value.  By default it is smart and will output an appropriate HTML <input/> element based on the type to be edited.  For example, it will generate <input type=”text”/> elements for the first four properties above (which are strings and integers).  It will generate a <input type=”checkbox”/> element for the final “IsActive” property – which is of type boolean.

In addition to supporting simple data-types, the Html.EditorFor() helper method also allows you to pass more complex objects with multiple properties to it.  By default it will loop over the public properties of the object and generate a <label>, <input/> element, and any appropriate validation message for each property it finds.  For example, we could re-write the above view to have just a single Html.EditorFor() call for the Customer object to conceptually output the same markup as above:

The strongly typed helpers allow you to optionally decorate the properties of the Customer ViewModel class with [DisplayName] attributes to control the label string that is output for each property used (for example: instead of having a label text of “IsActive” we could apply a [DisplayName(“Is Active Customer:”)] attribute). 

You can also add [ScaffoldColumn(false)] attributes to indicate that a particular property shouldn’t be rendered at all in scenarios like above where complex objects are passed to Html.EditorFor().

UI Helper Templating Support

The Html.EditorFor() and Html.DisplayFor() helper methods have built-in support for rendering both standard data-types as well as complex objects with multiple properties.  As noted above, they also support basic customization of rendering by applying attributes like [DisplayName] and [ScaffoldColumn] to the ViewModel.

Often developers want to be able to customize the output from UI helpers even further, though, and have total control over what is generated.  The Html.EditorFor() and Html.DisplayFor() helper methods support this via a templating mechanism that allows you to define external templates that can override and completely control the output rendered.  Better yet, you can customize the content rendered on a per-datatype/class basis.

With Preview 1 you can now optionally add an “EditorTemplates” and/or “DisplayTemplates” folder underneath either a \Views\[controllername] directory (if you want to customize the rendering for views used by a specific controller) or underneath the \Views\Shared folder (if you want to customize the rendering for all views and controllers in an application). 

You can then add partial template files to these folders to customize the output rendering performed on an individual datatype and/or class basis.  For example, below I have added an EditorTemplates folder underneath the \Views\Shared folder – and added three custom template files to it:

The “Customer.ascx” template above indicates that I want to customize the output anytime Html.EditorFor() is passed a Customer object (for example: I could customize the exact ordering/layout of the Customer properties).  The “DateTime.ascx” template above indicates that I want to customize the output anytime Html.EditorFor() is passed a DateTime property (for example: I might want to use a JavaScript datepicker instead of a plain textbox).  I could optionally add an “Object.ascx” template to the folder if I wanted to override the default rendering of all objects.

In addition to customizing rendering on a per-type basis, you can also add “named templates” to the folder.  A common scenario might be a “CountryDropDown” template that handles a string datatype – but instead of providing a standard textbox instead renders a <select> dropdownlist of country values that a user can pick from.  Below is what this editor template might look like:

We can explicitly indicate that we want to use the above template by passing its name as an argument when we invoke the Html.EditorFor() helper method.  For example, below in addition to specifying a lambda expression for our Country property, we are also specifying the name of the editor template to use when rendering it:

Alternatively, you can specify “UIHint” attributes on your ViewModel properties and types.  This allows you to indicate the default editor or display template to use in a single place, and have it be used in all views across your application (without having to explicitly pass it as an argument to Html.EditorFor). 

Below is an example of how to indicate using a UIHint attribute that the Customer.Country property (which is of type string) should by default use the CountryDropDown template when being rendered:

Once we set the above attribute on our ViewModel we no longer need to specify a template name explicitly when we use that property with Html.EditorFor().  And now when we hit refresh on our /Customers/Create URL our Country property will be rendered as a dropdown instead of a standard textbox:

Other Cool Features

ASP.NET MVC 2 Preview 1 includes a number of other small, but really nice, feature additions.  A few of my favorites include:

New [HttpPost] Attribute

It is pretty common with ASP.NET MVC to split up the handling of a URL across two action methods – one that handles GET requests and one that handles POST requests.

With ASP.NET MVC 1 you used an [AcceptVerbs(HttpVerbs.Post)] attribute to indicate the “Post” version of an action method:

This still works with ASP.NET MVC 2. Alternatively, though, you can also now take advantage of a terser [HttpPost] attribute that does the same thing:

Default Parameter Values

Handling optional parameters is a pretty common web scenario.  With ASP.NET MVC 1 you could handle optional parameters either by registering a custom routing rule and specifying a default value with it, or by marking an action method parameter as nullable and then adding code within your action method to handle whether it was null (and if so provide a default value).

ASP.NET MVC 2 Preview 1 now supports decorating action method parameters with the DefaultValueAttribute from the System.ComponentModel namespace.  This allows you to specify a parameter value that ASP.NET MVC should pass in if it is not present as part of the request.  For example, below is an example of how we could handle both the /Products/Browse/Beverages and /Products/Browse/Beverages?page=2 URLs – and have the “page” parameter value be “1” if it isn’t provided as part of the querystring:

VB today allows you to specify default parameter values directly within the VB language (avoiding the need to explicitly specify the DefaultValue attribute like above).  C# in VS2010 will also support default values with optional parameters – which will enable you to rewrite the above code simply as:

This should make handling default/optional scenarios really easy and clean.

Binding Binary Data

ASP.NET MVC Preview 1 adds support for binding base64-encoded string values to properties of type byte[] and System.Data.Linq.Binary.  There are now two overloaded versions of Html.Hidden() that can take these data-types.  These can be useful for scenarios where you want to enable concurrency control within your application and want to roundtrip timestamp values of database rows within your forms. 

Summary

Click here to download a .zip file that contains a ASP.NET MVC 2 project that implements the sample code I demonstrated in the above walkthrough.

Today’s build of ASP.NET MVC 2 is just a first preview.  More features will be coming in future previews, and the team expects to get a lot of feedback on ways to improve and enhance the release. 

The goal with doing these regular previews is to help make sure that this feedback process is open and that anyone who wants to participate can easily get involved.  Please post any feedback, suggestions or problems you have to the ASP.NET MVC Forum on www.asp.net.  You can also learn more about the release from Phil Haack’s MVC2 post, and from the Channel9 video Phil did with Scott Hanselman about the Preview 1 release.

Hope this helps,

Scott

P.S. I have been using Twitter more recently to-do quick posts and share links.  You can follow me on Twitter at: http://www.twitter.com/scottgu (@scottgu is my twitter name)

154 Comments

  • looks great!

    thanks and keep 'em coming;

  • Wow!!! It's really great....

  • Fantastic news!!! How about strongly-typed action generators? :( (to strongly-type the controller and action name)

  • When do you plan to incorporate asynchronous controllers?

  • @Mads,

    >>>>>> I know it's a little off-topic, but what VS2008 theme are you using?

    I have a slightly custom theme that I use. I will try and get it posted somewhere and update this comment thread with a link to it.

    Thanks,

    Scott

  • @Andrei,

    >>>>>> Fantastic news!!! How about strongly-typed action generators? :( (to strongly-type the controller and action name)

    That is on the list for future previews. We have been playing around with a few different approaches and are trying to figure out which approach feels best.

    Thanks,

    Scott

  • @Joe,

    >>>>>>> When do you plan to incorporate asynchronous controllers?

    That is still on the list of things todo for this release. The support isn't in preview 1 yet - but will hopefully show up in a future preview release.

    Thanks,

    Scott

  • default/optional scenarios are already clean by using nullable types. I don't really see any change here.

  • Hi Scott,
    Congratulations on the new release. The new features are really exciting. Thanks for your great post.

  • Thank you for this new release

  • Amazing! I assume the validators are fully I18N capable and can be shared between UI and Services?

    Don't spend too much time working on v2, release often such as we do not have to do a massive refactoring cycle (we definitively will as we do not like to have redundant lines in the code).

  • The MVC is doing an awesome job by releasing consistently. Congratulations on getting the preview 1 out the door.

  • Very nice. Can't wait until MVC V2 is out!

  • Any chance of a directory based areas implementation rather than having to create a new project? A convention based folder named Areas, with the appropriate directory structure inside would be nicer for some smaller projects that still have area concerns. Is there any reason why this could not work alongside the mvc 2 areas way of doing things?

  • Oh, it is so fast, and so exciting.

  • What about perfomance using 'Strongly Typed UI Helpers' ?

  • Will Html.RenderAction() be making an appearance in ASP.NET MVC V2?

  • Really exciting Areas, that is what I do need. I hope you fast release CTP version, and I can start new project :)

  • +1 for strongly typed actions.. Less reliance on magic strings and anonymous objects is a good thing.. Something like T4MVC's:

    Html.ActionLink("Hi", MVC.Users.Details(Model.UserID));

    or something new, like:

    Html.ActionLink("Hi", c => c.Details(Model.UserID));

    would be very welcome in the core MVC library/tooling.

  • Feature requests for strong typed helpers:

    - Add an IdFor and NameFor method so you can include it in javascript instead of strings (like MvcContrib).
    - Add something that puts a span with an id (like if customer name can't be edited, but you want to refer to it in javascript or watin tests).
    - Make the code that generates the Id for the html input helpers callable from non-view code. Again, useful for watin tests when you want to write values to edit fields.

  • Will this work with the VS 2010 beta?

  • Great news but I may wait a while before updating my articles. Though it doen't look like there would be much work required. I'm looking forward to the asynchronous version!

  • To go along with an earlier comment about strong-typing, EVERYTHING that can be should be strongly typed. I'd love to see the MVC team have a goal of zero strings :).

    John

  • Please make sure you have a non-attribute story for the validation.

    Attributes are unusable when your model classes come from LINQ to SQL.

  • I'm really excited to use Areas.. from day one, I've been wanting something like that!! Thank you!

  • Scott, about the ErrorMessage property of the validation attributes, is there going to be a way to point that to a resource file, because if we can't globalize & localize everything then we're going to need work-arounds to use MVC for public-facing sites, or fall back to WebForms.

  • I've met following bugs:
    If I create 2 areas: Admin, User.
    For Admin Area I create 2 controllers: Admin, Rubric
    For user area I create 2 controllers: User, Rubric
    So, when I want to run I have to copy views from areas to main project, and what I have:
    admin area views copied to main in Views\Admin, Views\Rubric.
    user area views copied to main in Views\Admin, Views\Rubric, files are replaced.
    If I try to use Views\Areas folder I have to do in such manner:
    ~/Views/Areas/Admin/Admin/Index.aspx
    ~/Views/Areas/Rubric/Rubric/Index.aspx
    ~/Views/Areas/User/User/Index.aspx
    ~/Views/Areas/Rubric/Rubric/Index.aspx
    so files are replaced again. What do I want:
    admin area views goes to /Views/Admin/{controllername}/{ViewName}

  • I really like the validation feature - that's going to be a massive time saver and it looks really clean.

  • Is it possible to handle globalization with DataAnnotations?
    I would like to display a message based on a specified culture, something like this:

    // Set culture based on http request
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("it-IT");

    // Get NAME_REQUIRED_MESSAGE from resource file using defined culture
    [Required(ErrorMessage = "{Resource NAME_REQUIRED_MESSAGE}")]

  • The templated helpers were a really nice touch and surprise. Digging into them now!

  • Awesome! I can't wait to use ASP.NET MVC V2. Thanks!

  • Nothing but win! I think Phil and the boys need a round of beer.

  • Great :) let's play with that thing now! It looks great that some Dynamic data features start to sneak in ASP.NET MVC :). That should help shut the mouth of people saying MVC is less productive. (Besides the fact that productivity is different from Rapid Development)

  • [Required(ErrorMessage = "Name Required")]
    What is solution for multi-language application?

  • Hi Scott,
    Looks interesting but is there anyway that you can pull the error messages from localised resources?
    [Required(ErrorMessage= GetLocalResourceObject(.....

    Thanks

  • I question the addition "UIHint" attribute. First, it seems to muddy the model of the customer...should it really be concerned with how it is displayed. Second, is that a UI hint for a "display" view or an "edit" view. For example, I may want to display the field as a simple label when displaying the customer details, but I want to display the drop down when I have gone into an "edit mode" (a separate view).

    I know it's one of the things that one could say take it or leave it, but I wonder if it promotes clarity in the code.

    What are your thoughts?

  • Wicked good stuff.

  • Very happy to see xVal's Data Annotations approach included in this release. I just showed my company this technique about a week ago, hoping it would gain wider adoption. This will certainly help convince a few :).

  • @andrexx,

    >>>>>> What about perfomance using 'Strongly Typed UI Helpers' ?

    We've done some performance optimizations already - but expect to do more in the future to cache the results of lambda based evaluations.

    Thanks,

    Scott

  • @Dominic,

    >>>>>> Will Html.RenderAction() be making an appearance in ASP.NET MVC V2?

    Yes - that is on the current plan for V2.

    Thanks,

    Scott

  • @Arnis,

    >>>>>> Are there any estimate when RTM could be ready?

    We haven't published a date yet - although we will support "go-live" deployment on later previews (meaning you can deploy even before the final RTM release).

    Thanks,

    Scott

  • @Mike,

    >>>>>> Will this work with the VS 2010 beta?

    Not with VS2010 Beta1 yet. ASP.NET MVC 2 will be built-into VS2010 Beta2 though.

    Thanks,

    Scott

  • @Rob,

    >>>>>>> Please make sure you have a non-attribute story for the validation. Attributes are unusable when your model classes come from LINQ to SQL.

    The "buddy class" approach I mentioned above works with classes generated by LINQ to SQL - allowing you to use DataAnnotations with them as well.

    Thanks,

    Scott

  • @John Mayer,

    >>>>>> Scott, about the ErrorMessage property of the validation attributes, is there going to be a way to point that to a resource file, because if we can't globalize & localize everything then we're going to need work-arounds to use MVC for public-facing sites, or fall back to WebForms.

    Yes - you can localize that today. In addition to specifying the string explictly you can alternatively provide a resource key. That allows you to fully localize the error messages. That is supported today with Preview1

    Hope this helps,

    Scott

  • @emanuele,

    >>>>>>> Is it possible to handle globalization with DataAnnotations?

    Yes - you can localize that today. In addition to specifying the string explictly you can alternatively provide a resource key. That allows you to fully localize the error messages. That is supported today with Preview1

    Hope this helps,

    Scott

  • Hi Scott,

    Is there anything new on the horizon for ASP.NET Webforms?

  • @Thale, @Dylan,

    >>>>>> Looks interesting but is there anyway that you can pull the error messages from localised resources?

    Yes - you can localize that today. In addition to specifying the string explictly you can alternatively provide a resource key. That allows you to fully localize the error messages. That is supported today with Preview1

    Hope this helps,

    Scott

  • @Brian Sherwin,

    >>>>>> I question the addition "UIHint" attribute. First, it seems to muddy the model of the customer...should it really be concerned with how it is displayed. Second, is that a UI hint for a "display" view or an "edit" view. For example, I may want to display the field as a simple label when displaying the customer details, but I want to display the drop down when I have gone into an "edit mode" (a separate view).

    In general I probably wouldn't use UIHint for pure model classes. But I do think it is useful for ViewModel classes that are designed to help with presentation generation. When used with those it allows you to keep your code DRY in a nice way.

    If you apply a template both the EditorFor and DisplayFor helpers will look for the appropriate template in their respective folders. They won't fail if it can't find one though - instead it will just fallback and use the next appropriate template. The benefit with this is that you can set UIHint once and have it apply for both edit and displays scenarios - and not write any code to have to special case if the template isn't there for one or the other scenarios (or even neither).

    Hope this helps,

    Scott

  • @Erwin,

    >>>>>> Is there anything new on the horizon for ASP.NET Webforms?

    Absolutely! I'll be doing a big blog post series soon that talks about the improvements to WebForms coming with ASP.NET 4.0. There are a bunch of great new non-MVC features coming as part of that release.

    Thanks,

    Scott

  • Hey Scott,

    What about support for SiteMap or something similar that makes our life easier when creating the main navigation menu??
    I have seen custom implementations that basically parse the SiteMap xml file and create the navigation links, but it would be great to have some native support for this !!!

    Great work, I love MVC !!!
    -Anthony

  • Great Great...
    Keep up the good job

  • I'd find this easier to follow if I could see the screen shots. Do I work for the only enterprise that blocks amazonaws.com? Could you host the images in the same domain? Maybe you could also work with Amazon to expose hosted data in a safe read-only domain that would not need to be blocked.

  • @ScottGu

    Hi Scott, can we have some strongly typed [Add Controller] dialog window support?
    I am asking for it because I want to customize the code generated based on the Model's Type.

    Thanks!

  • Very cool!

    Honestly I was expecting 1-2 items I could use along with others that I wouldn't care, but ... I see myself Using all of these!

  • Great post as always! Does the UI Helper Templating Support span over to cover the areas that are added to the solution too...or do they have to define their own templating?

  • I know this is not in golive, but aside from that and new features, have you changed the core to make any breaking changes or it is safe to use this preview to get advanced features in current production projects?

  • When creating the Templated Editors, why only go half way on the strong typing? In your example, you're strong typing the selector but not the view helper. Why not add an overloaded method with the following signature:

    EditorFor(Func selector, ViewUserControl control)

    With this, you could then make the control strong typed as well as follows:

    c.Country, new CountryDropDown()) %>

  • Very cool to see this growing. Some questions:

    1) What's the expectation for localization support? I see all those validation error messages as literals, can they come from a CurrentCulture-driven resource? Is there a helper for this already?

    2) I still see string literals in the code, those make me afraid. How can we apply a UIHint by referring to strong-typed class/attribute information instead of string literals? I want to leverage my compiler as much as possible to avoid typo-bugs.

    3) Regarding the validation support, are there model-level validation hooks in addition to property-level hooks? Can I specify things like 'conditional' validation when one property is related to another (i.e. this must be a valid state for the selected country, etc.)?

    4) In the handling of DefaultValues, you bring up a particular sticking point in many designs. What is the handling in place for things like a "date of death" that is a "nullable" value for live people, but if specified must "be in the past". I see this as related to default values because a common solution is to use the NullObject pattern and use (e.g. for date of death) DateTime.MaxValue. When that default is preset, we would want to render the value in the UI as "blank/greyed/etc". What's the intention for this sort of thing? Would we be able to write our own templated Html.EditorFor on a unique value-type containing the DateTime --since we can't derive from it :( grrrr.

    I guess what I'm (perhaps unreasonably) asking for is that we don't create another WebForms-like abstraction that doesn't address the issues of building non-trivial localizable, end-user-defined [by options at minimum] systems. I don't want the complete nebulous underbelly of MS's (very awesome) CRM framework, but I would like something pretty close :)

  • About RenderAction / RenderPartial, are you guys still going to create temporary System.Web.UI.Page objects to handle each ViewUserControls? We wanted to define views for several repeating structures but realized you guys were creating pages and calling the whole page life cycle for each one of those. This has a very negative performance impact; it would be great if that code path could be improved.

  • Hey,

    I like the data annotations so much. I think it should be standard in all code-generation based data access layers!

    But I feel something is not so great about the CountryDropDown.ascx. One good thing in the MVC to me (which can be achieved in other UI patterns also) is that everything is managed from within the Controller. Loading the countries in the way:



    when applied in a real world scenario with values coming from object filled with some data method or domain services, would make other dependency that is not managed by the Customer Controller.

    Of course you can always write something like this in the view:

    and in the Create() action write:
    var countries = new[] {"France", "Germany", "US", "UK"};
    ViewData["Counties"] = countries;
    but it's still not clean enough. You can not make the ViewData strongly typed for reuse with different controllers, and if you leave it up to magic strings, then you have ... ahh.. magic strings!

    While writing this, I didn't have much of thought about way to solve it. Passing domain object for the user control might be one solution. Thinking more, it looks exactly like the same issues with RenderPartial(). Using something like MVCContrib RenderAction() could be one solution (feels nice, except it makes things look like the same code behind model, where view is the markup, and Controller Action is the code behind).

    Thoughts?

  • Thanks Scott, I was sad when I saw Stephen Walther moving to the ASP.NET Ajax team. Now I see ASP.NET MVC framework stays alive! Keep up a good work!

  • Great stuff. This kind of thing is really needed and has been the subject of quite a bit of custom extension in our current projects.

  • Would someone shed a light on this MVC stuff? Wasn't this design/pattern created in 70's? Those days cross platform portability was almost non-existent.
    Why would you retro a platform like .NET to mimic something that was created in the 70's. I guess history does repeat itself. I have to find powder blue polyester suit to wear while coding this MVC stuff.

    Best regards,

    Curious

  • I'm very very excited!
    thank you this release.

  • wow Scott, Kudos to u and ur team

  • Scott,
    I like your VS Theme too you really should post the settings file ;) Would love to take it for a spin

  • Will this also stay in beta for long enough to take all interest out of it?

  • Looks good. How to do multi-field validations? For example, State+City OR ZIP is required? If City value is present, State is required.

  • How about having another strongly type-able object like Model that gets passed to the views. I think it would be a big advantage for views where you want to pass a class to edit (like Customer) but also another class (misc view data) that holds select lists and other data used only for presentation (like in drop down's). This way the "model" is the class to view/edit but the other data is "ride along" data to support the view. I think it would make for a better alignment with the post-backs as the post backs usually just need the Model class.

  • Ooooooh, this is great news for MVC fans !!!!!

    THANKS!

  • Really like the UIHint and DropDownList feature, checking it out right now and it seems that if you are editing an object and using the DropDownList UIHint the current value is not selected in the DropDownList during the edit.

  • ASP.NET MVC has been a shining example of collaboration between the ASP.NET MVC team and the .NET Community. We (the developers) really appreciate the efforts that have gone into the product, and for allowing us to provide feedback and be part of the solution.

    Thanks.

  • Good to see the validation stuff and looking forward the jquery plugins. Hopefully it could be better than xVal. BTW, this there any way that I can turn the validation off when binding the model, i.e. an attribute says [NoValidate] or somthing else. Thx. :P

  • Nice and short little intro, thanks for sharing it.

  • Hi Scott, looks good. I'm particularly pleased by the validation stuff; that's been something of a painful experience in v1. Can I ask that you guys are very careful to make sure that's as extensible as humanly possible? If I'm writing my validation rules using a different framework, it should be very easy for me to tell the client-side validation framework how to handle rules that don't exist in DataAnnotations; including custom messages.

    On the subject of extensibility, a replacable ModelBinderFactory (as opposed to the irreplacable Dictionary) would be super-cool - think NinjectModelBinderFactory; as would a separation between the ActionFilter attribute and the ActionFilter itself (in a similar way to the ModelBinders in v1). This is all to make it easier for me to Ninject properties into my ModelBinders and ActionFilters - eg. I currently have a base IocActionfilterAttribute that calls Inject on itself, which just feels plain wrong.

    I haven't yet looked at this version, beyond reading this post, so if you're way ahead of me then please feel free to ignore :).

  • This is both good news and bad news. We are just starting a 6 month project that needs the connected server side validation with JQuery validation. The good news is that you guys are writing it, the bad news is that its not going to help us in this project and we are going to have to spend a bunch of time creating it. I'm excited that MVC is moving forward quickly!

  • Love the new validation support!!!

    I haven't tried the UI Helper templates yet, but I think that'll make my life easier!!

    I learned MVC 2 weeks ago, and I'm already building apps today. MVC rocks!! Please keep the instruction coming regarding LINQ to SQL/Enitites. It really helps those of us who are new to the framework. Thanks!!

  • With a view form binding to the underlying data, how would I go about encoding display data to prevent XSS exploits? Similarly, for input fields, will I need to specifiy a regex validator individually for each field, or can I specify a validation function instead? Thanks.

  • In asp.net mvc 1, i feel it is not so easy to manage folders like the following:


    ----
    --------
    --------
    --------
    --------
    --------

    I have to define several controllers to manage , how to make it easy in version 2?

  • Is there a way to set the UI Helper Templating dropdownlist's "selected" attribute in the example above? i.e. for an "edit" page.

  • Woah, that's some good stuff you have here!

    Looking forward to it

  • Do you have a sample of the new Buddy Class? I'd like to see this in action.

  • Looks like MVC 2 would be best thing in the world!!
    We are already using MVC 1 for our projects and we are happy.
    After demonstrating MVC 2 Preview 1, I could say you guys did a lot of things we expected!

    Thanks a lot, Scott!

  • I have the same question as REX

    "Love the support for validations with DataAnnotations, but I'm having a hard time picturing how to leverage them against LINQ2SQL model classes via a "buddy class" as suggested. I've got the generated core L2S model and I've got a corresponding view model that may or may not look quite like the core model that essentially does left-hand right-hand copying of properties (setting things like Automapper aside for the moment). Should the buddy class be yet another (third) representation of the model, doing more L/H - R/H with properties? Should it live between the core model and the view model? It seems like I would be better off putting DataAnnotations in the view model, but now am I making the view model too smart?

    How else might the implementation of a buddy class look?
    "

  • Can anyone recommend a good study source for it?

  • I am not convinced that putting UI hints and validation directly in my business object is the best thing to do. In fact it goes against single responsibility principal. The UI hint should be in a view model and validation should be in a different class. You can have different validation for different circumstances based on the task at hand even though you may be using the same business object. Putting on the business object directly is only going to cause issues at a later date in the product lifecycle.

  • Awesome Stuff!
    Mvc was by far my favorite new Microsoft platform/subsystem and I haven't even caught up with the full suite of V1 features (and we've been using since Preview 2 way back more than a whole year ago). I'm a fan of the new features. They fit nicely into the enterprise application space and help make Asp.Net MVC a more sophisticated solution than even rails even if rails still has a little more rabbit in your hat magic happening.

    I'd like to see those validation attributes trigger jQuery.validate registrations, in addition to the server side checks.

    Thanks so much for the DefaultValue attribute. I was simply using nullables and then repeating the same code over and over. I should have realized the error in my ways :)

    rock on!

  • Anyone working on the drag-drop type of custom controls? GridViewMVC, etc. Anything RAD?

  • One thing that I disagree with, philosophically speaking. Having the validator attributes in the Model or ViewModel makes sense to me in that you're more completely describing the data. The UIHint, though is out of place. UI stuff should not be in the Model.

    What I'd like to see is an expansion of using the UIHint in the View. perhaps the UIHint parameter to the Html.EditorFor() method could actually be a dictionary list. You'd wind up with syntax something like:

    c", new UIHintList({"c=>c.Country", "CountryDropDownList"})) %>

    Steve G.

  • How do the new validation features handle scenarios where the same bit of data is validated differently depending on the validation context? e.g.

    When creating or updating a customer (create context, update context) it's extremely common to have them confirm their email address in a separate field. This email confirmation input isn't part of the model it's purely to assist correct user input, this might be called a virtual property. When a user logs in using their email address (read context) the validation shouldn't try and match the email against a confirmation input.

    As far as I am aware all DataAnnotation attributes are fired when validating, or is there some sort of partial validation feature?

    Thanks,

    John

  • Hi Scott,

    The roadmap for V2 looks promising, espeically area and async controller support. Are there any plans to include the following features within the version 2 release:
    1. SubControllers: Enabling improved controller reuse?

    2. Compiled Views: Which would make it really easy share common 'Area' projects (ie: Forums), so that to include a Forum area in your MVC project, you'd simply reference a 'MyCompany.Mvc.Forums.dll' assembly, and it would contain all controller logic and views you'd need to inject forum capability into your website.

    I'm particularly interested in compiled views, (which is already partially supported if you use the 'Spark' view engine) and the ability to deploy entire functional areas of a website using a single assembly. I think such a feature would encourage community input to deliver common MVC features that could be downloaded and used to really speed development time.

    Keep up the good work, Thanks!

    Adam.

  • Is it rational to implement ASP.NET MVC 2 in big web-project right now?

  • Great blog, I just discovered it and have signed up. One small request: Could you put a posting date at the top of each entry? I found something interesting via a Google search but did not know when it was written. Sometimes I get confused with older posts that I think are current.

    Many thanks -- I'm new to VS and searching for help on CSS - your article here...

    http://weblogs.asp.net/scottgu/archive/2007/07/25/vs-2008-web-designer-and-css-support.aspx

    ... was a godsend. Thanks!

  • @Anthony,

    >>>>>> What about support for SiteMap or something similar that makes our life easier when creating the main navigation menu??

    >>>>>> I have seen custom implementations that basically parse the SiteMap xml file and create the navigation links, but it would be great to have some native support for this !!!

    It is a good suggestion. You can use the existing ASP.NET SiteMap API today with ASP.NET MVC, but there aren't automatic helpers for it yet. I believe the MVCContrib project, though, might have something already to do this that is worth checking out.

    Hope this helps,

    Scott

  • @Matthew,

    >>>>>>> I'd find this easier to follow if I could see the screen shots. Do I work for the only enterprise that blocks amazonaws.com? Could you host the images in the same domain? Maybe you could also work with Amazon to expose hosted data in a safe read-only domain that would not need to be blocked.

    Sorry about this - I'm trying to figure out how to avoid this. I am probably going to move my images somewhere else soon - but for right now that is the only server I can use.

    Thanks,

    Scott

  • @Soe Tun,

    >>>>>> Hi Scott, can we have some strongly typed [Add Controller] dialog window support?

    >>>>>> I am asking for it because I want to customize the code generated based on the Model's Type.

    I'd like to see this too. I'm not sure when it will show up just yet - but it is a good suggestion.

    Thanks,

    Scott

  • @Andrew,

    >>>>>>> Great post as always! Does the UI Helper Templating Support span over to cover the areas that are added to the solution too...or do they have to define their own templating?

    I believe you can put the templates under the shared folder of the application and have them span everywhere.

    Hope this helps,

    Scott

  • @Toncij,

    >>>>>> I know this is not in golive, but aside from that and new features, have you changed the core to make any breaking changes or it is safe to use this preview to get advanced features in current production projects?

    There will probably be some breaking changes by the time of the next preview - although they will most likely be small updates/tweaks. I believe the team is hoping that the next preview will have a go-live license.

    Hope this helps,

    Scott

  • @Jim Wooley,

    >>>>>> When creating the Templated Editors, why only go half way on the strong typing? In your example, you're strong typing the selector but not the view helper.

    That is an interesting suggestion. I'll forward it along to the team to look at. I think the main reason it isn't strongly typed today is because view templates (and any .aspx/.ascx markup files) are compiled at runtime and so the exact name of the resulting class isn't known.

    Hope this helps,

    Scott

  • @Marc Brooks,

    >>>>>>> 1) What's the expectation for localization support? I see all those validation error messages as literals, can they come from a CurrentCulture-driven resource? Is there a helper for this already?

    All of the DataAnnotation properties can be set using resource files as well. So it should be localization friendly today.

    >>>>>>>> 2) I still see string literals in the code, those make me afraid. How can we apply a UIHint by referring to strong-typed class/attribute information instead of string literals? I want to leverage my compiler as much as possible to avoid typo-bugs.

    At some point you do need to associate a value to a string key (that indicates the template name). I need to check but you might be able to have the UIHint reference a static field though which contains it - in which case the UIHint declaration would be compiler-checked.

    >>>>>>>>> 3) Regarding the validation support, are there model-level validation hooks in addition to property-level hooks? Can I specify things like 'conditional' validation when one property is related to another (i.e. this must be a valid state for the selected country, etc.)?

    Yes - you can apply DataAnnotations at both the property and class level.

    >>>>>>>> 4) In the handling of DefaultValues, you bring up a particular sticking point in many designs. What is the handling in place for things like a "date of death" that is a "nullable" value for live people, but if specified must "be in the past". I see this as related to default values because a common solution is to use the NullObject pattern and use (e.g. for date of death) DateTime.MaxValue. When that default is preset, we would want to render the value in the UI as "blank/greyed/etc". What's the intention for this sort of thing? Would we be able to write our own templated Html.EditorFor on a unique value-type containing the DateTime --since we can't derive from it :( grrrr.

    >>>>>>>> I'd probably recommend making the value nullable, and then have a template that you apply that customizes its presentation.

    Hope this helps,

    Scott

  • @Jonathan,

    >>>>>>> About RenderAction / RenderPartial, are you guys still going to create temporary System.Web.UI.Page objects to handle each ViewUserControls? We wanted to define views for several repeating structures but realized you guys were creating pages and calling the whole page life cycle for each one of those. This has a very negative performance impact; it would be great if that code path could be improved.

    The framework does create a page for rendering - but I believe the page is reused across all of the partials. In general most things are cached, and the page life-cycle is not evaluated (instead it just renders) so the performance is pretty good.

    Hope this helps,

    Scott

  • @Mohammed,

    >>>>>>> But I feel something is not so great about the CountryDropDown.ascx. One good thing in the MVC to me (which can be achieved in other UI patterns also) is that everything is managed from within the Controller. Loading the countries in the way....when applied in a real world scenario with values coming from object filled with some data method or domain services, would make other dependency that is not managed by the Customer Controller.

    I did it that way in the post because I thought that would be the easiest to read - and I only hard-coded in 4 countries (not very real world).

    For something like countries I'd probably recommend encapsulating them within a class with a static property that the view accesses (like Countries.AllCountries) - that way you can easily encapsulate and re-use them, and the controller doesn't need to explictly pass them.

    Hope this helps,

    Scott

  • @Ryan,

    >>>>>> It'd be nice to have a FormFor(model) helper that would automagically output the editors for all properties of the model. It'd make scaffolding extremely easy.

    Conceptually we have this today too - you can call Html.EditorFor(model) and it scaffolds all properties.

    Hope this helps,

    Scott

  • @mgutz,

    >>>>> Looks good. How to do multi-field validations? For example, State+City OR ZIP is required? If City value is present, State is required.

    You can actually apply the DataAnnotations at the class level - in which case they can apply towards multiple properties.

    Hope this helps,

    Scott

  • @Angel,

    >>>>>> What about support other validators like Nhibernate or Castle for server and automatic client validations?

    We are designing the client-side validation system so that it will be easy to plugin any validation framework. So yes - NHibernate and Castle will work great too.

    Hope this helps,

    Scott

  • @Brennan,

    >>>>>> How about having another strongly type-able object like Model that gets passed to the views. I think it would be a big advantage for views where you want to pass a class to edit (like Customer) but also another class (misc view data) that holds select lists and other data used only for presentation (like in drop down's). This way the "model" is the class to view/edit but the other data is "ride along" data to support the view. I think it would make for a better alignment with the post-backs as the post backs usually just need the Model class.

    Yes - you can use a more complex ViewModel to accomplish this. Alternatively I also sometimes just use static properties on classes to pass along lists (like states and countries).

    Hope this helps,

    Scott

  • @Paul,

    >>>>>>>> Hi Scott, looks good. I'm particularly pleased by the validation stuff; that's been something of a painful experience in v1. Can I ask that you guys are very careful to make sure that's as extensible as humanly possible? If I'm writing my validation rules using a different framework, it should be very easy for me to tell the client-side validation framework how to handle rules that don't exist in DataAnnotations; including custom messages.

    Yes - definitely. We are working to make sure the client-side validation support can work with any validation framework.

    >>>>>>>> On the subject of extensibility, a replacable ModelBinderFactory (as opposed to the irreplacable Dictionary) would be super-cool - think NinjectModelBinderFactory; as would a separation between the ActionFilter attribute and the ActionFilter itself (in a similar way to the ModelBinders in v1). This is all to make it easier for me to Ninject properties into my ModelBinders and ActionFilters - eg. I currently have a base IocActionfilterAttribute that calls Inject on itself, which just feels plain wrong.

    Good suggestion - I'm not entirely sure what the status of this is - but will forward to the team.

    Thanks,

    Scott

  • @Bill,

    >>>>>>> With a view form binding to the underlying data, how would I go about encoding display data to prevent XSS exploits? Similarly, for input fields, will I need to specifiy a regex validator individually for each field, or can I specify a validation function instead? Thanks.

    By default ASP.NET MVC checks for XSS attacks and denies input like that. Having said that, I'd still recommend that you check yourself to be careful about this, and always HTML encode output to ensure that even if an XSS input gets in your page doesn't redisplay it.

    Hope this helps,

    Scott

  • @C.T.

    >>>>>>> In asp.net mvc 1, i feel it is not so easy to manage folders like the following:

    Have you thought about splitting the functionality up across multiple controllers instead?

    Thanks,

    Scott

  • @dizzguy,

    >>>>>> Is there a way to set the UI Helper Templating dropdownlist's "selected" attribute in the example above? i.e. for an "edit" page.

    Yes - the SelectedList object has a selected or currentvalue property on it that you can use. By default above it will automatically select the item based on the first param passed to the Html.DropDownList helper.

    Hope this helps,

    Scott

  • @Lakario,

    >>>>>>> Do you have a sample of the new Buddy Class? I'd like to see this in action.

    Here is a pointer to a sample that shows you how to use buddy classes: tinyurl.com/buddyclasses

    Hope this helps,

    Scott

  • @BsvVeen,

    >>>>>>> How else might the implementation of a buddy class look?

    Here is a pointer to a sample that shows you how to use buddy classes: http://tinyurl.com/buddyclasses

    Hope this helps,

    Scott

  • @SteveG,

    >>>>>>> One thing that I disagree with, philosophically speaking. Having the validator attributes in the Model or ViewModel makes sense to me in that you're more completely describing the data. The UIHint, though is out of place. UI stuff should not be in the Model.

    In general I wouldn't recommend putting UIHint in your model. But I do think it is appropriate in a ViewModel - since those classes are designed with UI in mind.

    >>>>>>> What I'd like to see is an expansion of using the UIHint in the View. perhaps the UIHint parameter to the Html.EditorFor() method could actually be a dictionary list. You'd wind up with syntax something like:

    c", new UIHintList({"c=>c.Country", "CountryDropDownList"})) %>

    The good news is that you can logically do this today - you can create a template for the customer and then specify an explicit template for any of the fields you want as a second argument to Html.EditorFor().

    Hope this helps,

    Scott

  • @SteveG,

    >>>>>>> One thing that I disagree with, philosophically speaking. Having the validator attributes in the Model or ViewModel makes sense to me in that you're more completely describing the data. The UIHint, though is out of place. UI stuff should not be in the Model.

    In general I wouldn't recommend putting UIHint in your model. But I do think it is appropriate in a ViewModel - since those classes are designed with UI in mind.

    >>>>>>> What I'd like to see is an expansion of using the UIHint in the View. perhaps the UIHint parameter to the Html.EditorFor() method could actually be a dictionary list. You'd wind up with syntax something like:

    c", new UIHintList({"c=>c.Country", "CountryDropDownList"})) %>

    The good news is that you can logically do this today - you can create a template for the customer and then specify an explicit template for any of the fields you want as a second argument to Html.EditorFor().

    Hope this helps,

    Scott

  • @John,

    >>>>>> When creating or updating a customer (create context, update context) it's extremely common to have them confirm their email address in a separate field. This email confirmation input isn't part of the model it's purely to assist correct user input, this might be called a virtual property. When a user logs in using their email address (read context) the validation shouldn't try and match the email against a confirmation input.

    The DataAnnotations are mostly useful for basic input level validation. For more complex validation that is context dependent I'd probably recommend using a different validation approach - either using imperitive code or a richer validation framework. The good news is that the MVC helpers are agnostic to the validation framework used, so you can integrate another one in and still use the client-side validation features and HTML validation helper methods.

    Hope this helps,

    Scott

  • @Adam,

    >>>>>>> The roadmap for V2 looks promising, espeically area and async controller support. Are there any plans to include the following features within the version 2 release:

    >>>>>>> 1. SubControllers: Enabling improved controller reuse?

    This one is on the bubble right now.

    >>>>>>>> 2. Compiled Views: Which would make it really easy share common 'Area' projects (ie: Forums), so that to include a Forum area in your MVC project, you'd simply reference a 'MyCompany.Mvc.Forums.dll' assembly, and it would contain all controller logic and views you'd need to inject forum capability into your website. I'm particularly interested in compiled views, (which is already partially supported if you use the 'Spark' view engine) and the ability to deploy entire functional areas of a website using a single assembly. I think such a feature would encourage community input to deliver common MVC features that could be downloaded and used to really speed development time.

    We have an issue with compiled views today in that the VirtualPathProvider class that ASP.NET uses can't be used in partial trust scenarios. We are fixing this with ASP.NET 4.0 - at which point we'll be able to deliver a really nice compiled view solution.

    Hope this helps,

    Scott

  • Great stuff and thanks. How about going a step further with the validation attributes?

    - Infer basic validation based on SQL columns in Linq-to-SQL, and have the attributes be part of the code-gen. Integers, non-nulls, max length of strings, etc. This could be an option in the Linq-to-SQL designer.
    - Generate "filtered" fields in the UI. A bit of OnKeyPress magic so that non-numeric characters can't be entered for integers, for example.

  • Hi,

    Loving the new changes in v2 preview 1 but I'd just like to share some thoughts before the product gets locked down.
    I'm not really keen on the buddy class method. Would it be considered to add some kind of 'metadata context' that you can then use to decorate your classes.
    e.g
    MetaContext.Current.Model(c => c.Name, new RequiredAttribute(ErrorMessage = "Name Required")).

    It just seems a bit more DRY to me, for example in the case of property name changes. Also you would get compile-time checking of mismatched names rather than runtime

    Also for the templated editors would it be possible to pass a little more metadata? Specifically I'm thinking of the class and property name, a reference to the model that the property belongs to, and the attributes that were applied to the property. This is to enable scenarios like setting the maximum length of a text box, setting it's background colour if it is a required field, or maybe even setting watermark text. It would also mean not having to type ViewUserControls to object if wanting to pass a value type such as datetime, as it would now be wrapped by a class such as MetaData.
    The reference to the model object and the property name are so in the controller I could store dropdown data per object and property in the viewdata and then retrieve them to build the dropdown later. This is for scenarios such as status where the options offered by a dropdown may vary by the objects state and not just be generic for the class. This method would allow be to prepare that info ahead of time and not have the view query back for supporting data.

    Sorry for the long comment, and I hope it makes some kind of sense. Thanks as always to you and the team for your hard work.

    Kind regards,
    Paul

  • @ScottGu,

    >>>>>>> The DataAnnotations are mostly useful for basic input level validation. For more complex validation that is context dependent I'd probably recommend using a different validation approach - either using imperitive code or a richer validation framework. The good news is that the MVC helpers are agnostic to the validation framework used, so you can integrate another one in and still use the client-side validation features and HTML validation helper methods.

    That's a real shame to hear, it would seem to me that DataAnnotations are pretty useless. The scenario I described is a pretty trivial, and extremely common, validation example. I can't think of many instances where you are creating a new user and would want to check that the email is valid, but not check that they have entered their email correctly. If DataAnnotations fall over on this type of thing, and don't have knowledge of what context they are being called in, I can't see much use for them.

    It would be great if they could do something like:

    [Required(ErrorMessage = "Email required", Context = new string[]{"Create","Update","SomeCustomValue"})]
    [Confirm(ErrorMessage = "Email must match", Virtual = "ConfrimEmailInputName", Context=new string[]{"Create","Update"})]

    ModelState.IsValid("Create")

    Thanks,

    John

  • Thanks a lot scott,
    it looks great features on the new MVC specialy for the validations and the way for creating the form.

    Best Regards

  • Any chance we'll see a command line scaffold capability to generate views, etc... based on a model ?

  • yes, it is more user friendly for webmasters and developers on this ASP.NET MVC version 2 compared to version 1. Cheers!

  • To Scott
    ------quote start---------------
    @C.T.

    >>>>>>> In asp.net mvc 1, i feel it is not so easy to manage folders like the following:

    Have you thought about splitting the functionality up across multiple controllers instead?

    Thanks,

    Scott
    ------quote end---------------

    thanks for your reply :)

    yes, the folders like this:


    ----

    --------

    --------

    --------

    --------

    --------

    and the *controllers what i use in my project now like this:

    MyAccountController.cs
    MyBookingController.cs
    MyFavoriteController.cs
    MyPointController.cs
    MyProfileController.cs
    ...
    ...
    ...
    and i made the MapRoute like this:

    //--------------------------
    routes.MapRoute(
    "MyFavorite", // Route name
    "{langCode}/MyAccount/MyFavorite/{action}/{id}", // URL with parameters
    new { langCode = "zh-cn", controller = "MyFavorite", action = "Index", id = "" } // Parameter defaults
    );

    routes.MapRoute(
    "MyPoint", // Route name
    "{langCode}/MyAccount/MyPoint/{action}/{id}", // URL with parameters
    new { langCode = "zh-cn", controller = "MyPoint", action = "Index", id = "" } // Parameter defaults
    );

    ...
    ...
    ...
    //--------------------------

    if in a big project, i feel it is not so easy to manage so MANY *controllers and so many MapRoutes

    how about ONE FOLDER ONE CONTROLLER?

  • Great news! Lots of new features and updates!

  • Thanks for the reply, Scott,

    >>>>>>> With a view form binding to the underlying data, how would I go about encoding display data to prevent XSS exploits? Similarly, for input fields, will I need to specifiy a regex validator individually for each field, or can I specify a validation function instead? Thanks.

    >>By default ASP.NET MVC checks for XSS attacks and denies input like that. Having said that, I'd still recommend that you check yourself to be careful about this, and always HTML encode output to ensure that even if an XSS input gets in your page doesn't redisplay it.

    >>Hope this helps,

    >>Scott

    But perhaps my question wasn't clear. I wasn't asking if I should still take basic security measures in my code, I was asking how those measures would be implemented against this view structure. I've found most of my answers through further reading, including a posting of yours from last Sept. regarding business rule validation in preview release 5, so thanks for that.

  • Thanks scott !!!

    New MVC has great features. Thanks for sharing !!!

  • Regarding DataAnnotations validation, how does one support a "Cancel" button that submits the form without any validation?

  • Disregard my previous question. I did something foolish in my code. ;)

  • Hi Scott!

    MVC v1 is really great, but some things are missing (in WebForms, too).

    First thing is the areas feature, which you introduced in v2.
    - Is it possible to have nested areas, e. g. in your example to have a Blogs/Statistics or Blogs/Admin area or an other simple way to get these urls working and mapped correctly for incoming requests?
    - Can I update the code (assemblies, as views are no problem) of one area to my server independent from other areas/the root area? I guess this requires that each area has it's own bin folder containing the area related assemblies but also uses assemblies in the root bin folder. Looking for assemblies then might occur from deepest bin folder up to parent bin folder, GAC. Is this possible to implement? Large ASP.NET / ASP.NET MVC based company websites always have the problem when one thing has to changed or one bug to be fixed immediately in the code, you have to stop the whole site for replacing one assembly in the bin folder. Otherwise I didn't found a good way/tutorial to split the site on several subdomains or at least different independent IIS applications which share session & application state etc.

    Second thing is about rendering views. Some times it would be very helpful to get the rendered view content back as string or StringBuilder or written into a provided stream instance instead of written directly to the HTTP response out stream. An example is to use the view infrastructure for generating email content or redirecting it to somewhere else, a html to pdf component or whatever... the MVCContrib project contains an email service which renderes a view using the normal view rendering system, captures the output by attaching a MemoryStream instance as filter to the response output and processing the stream content. But this way has a very big problem: It uses the same HTTP response stream as the current controller which called the email service. Because the output has to be flushes before attaching the filter and after removing it you aren't able to do reirects or other stuff which requires http headers to be written. So if you send a HTTP POST to an action which generates a email and sends it you cannot redirect to another action depending on values which do not exist before calling the email service, e. g. email send status.

  • Hi

    I am just downloaded this MVC V2 and tried it out.

    Now I have some quoestions:
    1. Is the source code open for everyone? - or for CodeZone Member
    2. Can the Controller Class communicate with other controllers in a application?
    3. VS 2010 and VS 2012 : is compatible?

    Can anyone help me in answering these questions?

    Thanks in advance

    Chrs
    CholonKid

  • Hello Scott,
    Nice work for v2.
    I have a question about DataAnnotation and UIHint : How can I modify this at runtime ?

    Example :

    I know that property Name has StringLength of 50 - and with DataAnnotations.StringLength I can easily put this. But I want also not "re-make"/recompile the application if someone decide that StringLength can be 70
    ? Also, how can I internationalize the message of StringLength ?

  • The area support feature is really great! We're currently using JSF with Facelets and a sophisticated build engine to achieve a similar result but this is really a lot better on all ends.

    There's just one thing I'd like to see in the future and that's the option to create controllers with the same name in separate projects. They'd differ in namespace of course (for example Main.Controllers.HomeController and Products.Controllers.HomeController). This way there would be no need to name the main entry point for an area any different than what it really should be - it's the Home of a module.

    Other than that I personally adore this framework! Great job!

  • Hi @ScottGu

    I have an ADO.NET Entity Model in the MVC project.
    When I create a partial class to put [DisplayNameAttribute] on top of a property inside my own partial class, I am getting this error.

    ERROR: The type 'TestProject.Models.Customer' already contains a definition for 'FirstName'.


    public partial class Customer
    {
    [DisplayName("First Name")]
    public string FirstName { get; set; }
    }


    How can I work around the problem with Entity Framework model classes?

  • Does this mean that service layers really aren't required now that DataAnnotation Validation support is available? Also, is it wise to use DataAnnotation Validation against a custom-build model? i.e.

    [Column]
    [Required(ErrorMessage="Field required!")]
    public int MyField { get; set }

  • Scott,

    Love the direction of MVC. One question, in MVC 2, you've changed the signature for GetControllerInstance from just System.Type to System.Web.Routing.RequestContext and System.Type. Is intentional and permanent? It's causing problems with Castle that I'm not sure yet how to handle.

    Thanks!
    Patrick

  • Scott, you wrote that a new futures library would be uploaded that brings e.g. ValidationMessageFor(). In codeplex there seems to be still the old version though. When will the new version be available?

  • Great stuff Scott and Team!

    In release 2, you've changed the signature/parameters for GetControllerInstance, do you expect the new signature with RequestContext to stay going forward?

    Thanks!
    Patrick

  • Could you post the download link to the futures assembly that contains the new ValidationMessageFor() helper method? It seems not to be on codeplex.

  • Hi again,

    UIHint looks like a really promising feature. For your example, isn't this:

    Customer customer = new Customer();
    customer.Country = "US";
    return View(customer);

    supposed to preselect the US entry?

    Could you also write on how to best load drop down values from a database? Should this go into a HtmlHelper extension class or are there superior ways?

    cheers,

    Stephan

  • "It doesn’t include any tool support yet (right now you need to manually add a build task to create an area project and set it up). Future preview releases will include tooling support, and expand and refine the feature-set further."

    Can you talk about this further? I want to create a Area project.

  • Hello! Can you give me your color settings of visual studio?

  • Scott, as usual, you continue to impress me. Very nice (and very much appreciated) work. I do have a quick question.
    Do the Html.EditorFor and Html.LabelFor methods add the equivalent of Html.Encode functionality behind the scenes to prevent Cross Site Scripting?

  • Which one is better going forward-MVC or Dynamic Data?

  • Thanks, I downloaded it, I overview

  • Is there any way to avoid large keystrokes of data in textfields instead of giving an error message ? ie prevent users from inputting after a limit rather than give an error

  • Hello, the image not look, is very important, can you upload ?,
    thanks

  • I am on my second MVC app and what a joy it is working with this stuff. Are you guys planning on some form of integration with expression, that would be sooooooo nice!!!

  • Sorry if this is newbie. Ok with globalization with error messages, but how about just literal strings that appear on Html. Is there any support(like the Generate Local Resource..loved it) available for Asp.net forms.Thanks


  • I have created a TextBox object in controller and set the properties of height, width etc...

    TextBox model = new TextBox();
    model............

    In the view i'm creating a textbox how can i use model to the textbox.

  • Hi,

    If we want to validate a form through modelstate validations (for example for login), how can we localize the validations? the GetLocalResourceObject or GetGlobalResourceObject is not accessible in the controller class...

  • Will MVC v2 have the ability to post back and update a parent record details together with the child record details. Doesn't seem to be possible in v1 (maybe already possible!!)

  • how would i use (or should I use) body classes in N-tier scenarios?I want validations on the web layer or service layer, but that means a reference to the entity model which is wrong...

  • This is again, another excellent article from Scott. Well done and congratulations, Scott!

    I have my site developed in ASP.NET MVC version 1 and this site is currently hosted at http://www.asphostcentral.com. Even though this host has supported the latest ASP.NET MVC v2, I still have not had a chance to "upgrade" to it. I certainly look forward to any new MVC development first before decising to "upgrade" my site.

    :)

  • Why silly UIHint???? Why not something easy to understand? eg. UITemplate??????????????

Comments have been disabled for this content.