Exploring the ASP.NET MVC 2 futures assemby

The future is cloudy! The latest preview of ASP.NET MVC 2, preview 2, has been released on CodePlex last week. All features of the preview 1 version are still in, as well as some nice novelties like client-side validation, single project areas, the model metadata model, … You can read more about these here, here and here.

Sure, the official preview contains some great features of which I’m already a fan: the model and validation metadata model is quite extensible, allowing the use of DataAnnotations, EntLib, NHibernate or your own custom validation logic in your application, while still being able to use standard model binders and client-side validation. Next to all this, a new version of the MVC 2 futures assembly was released on CodePlex. And oh boy, there’s some interesting stuff in there as well! Let’s dive in…

Quick note: the “piece de resistance” is near the end of this post. Also make sure to post your thoughts on this “piece”.

kick it on DotNetKicks.com

Controls

There’s not much that has changed here since my previous blog post on the MVC futures. Want to use a lightweight TextBox or Repeater control? Feel free to do so:

[code:c#]

<p>
    TextBox: <mvc:TextBox Name="someTextBox" runat="server" /><br />
    Password: <mvc:Password Name="somePassword" runat="server" />
</p>
<p>
    Repeater:
    <ul>
    <mvc:Repeater Name="someData" runat="server">
        <EmptyDataTemplate>
            <li>No data is available.</li>
        </EmptyDataTemplate>
        <ItemTemplate>
            <li><%# Eval("Name") %></li>
        </ItemTemplate>
    </mvc:Repeater>
    </ul>
</p>

[/code]

Asynchronous controllers

Yes, I also blogged about these before. Basically, asynchronous controllers allow you to overcome the fact that processing-intensive action methods may consume all of your web server’s worker threads, making your webserver a slow piece of software while it is on top-notch hardware.

When using asynchronous controllers, the web server schedules a worker thread to handle an incoming request. This worker thread will start a new thread and call the action method on there. The worker thread is now immediately available to handle a new incoming request again.

Get some REST!

Again: I already blogged on this one: REST for ASP.NET MVC SDK. This SDK now seems to become a part of the ASP.NET MVC core, which I really think is great! The REST for ASP.NET MVC SDK adds “discovery” functionality to your ASP.NET MVC application, returning the client the correct data format he requested. From the official documentation:

  1. It includes support for machine-readable formats (XML, JSON) and support for content negotiation, making it easy to add POX APIs to existing MVC controllers with minimal changes.
  2. It includes support for dispatching requests based on the HTTP verb, enabling “resource” controllers that implement the uniform HTTP interface to perform CRUD (Create, Read, Update and Delete) operations on the model.
  3. Provides T4 controller and view templates that make implementing the above scenarios easier.

Let’s come down to business: the REST SDK is handy because you do not have to care about returning a specific ActionResult: the SDK will automatically check whether a ViewResult, JsonResult, XML output or even an Atom feed is requested by the client. ViewData will automatically be returned in the requested format. Result: cleaner code, less mistakes. As long as you follow conventions of course.

Other stuff…

Yeah, I’m lazy. I also blogged on this one before. Check my previous blog post on the MVC futures for nice stuff like more action method selectors (like [AcceptAjax] and others), more HtmlHelper extensions for images, mailto links, buttons, CSS, … There’s more action filters as well, like [ContentType] which specifies the content-type headers being sent out with an action method.

There’s also donut caching, allowing you to cache all output for an action method except a specific part of the output. This allows you to combine cached views with dynamic content in quite an easy manner.

More new stuff: the CookieTempDataProvider, allowing you to turn of session state when using TempData. There’s also the [SkipBinding] attribute, which tells the ModelBinder infrasructure to bind all action method parameters except the ones decorated with this attribute.

ViewState!

ViewState gone evil! Got you there, right? The ASP.NET MVC team has been screaming in every presentation they gave in the past year that there was no such thing as ViewState in ASP.NE MVC. Well, there is now… And maybe, i will be part of the future MVC 2 release as well. Let’s first have a look at it and afterwards discuss this all…

On every view, a new HtmlHelper extension method named “Serialize” is present. This one can be used to create a hidden field inside a HTML form, containing a serialized version of an object. The extension method also allows you to pass a parameter specifying how the object should be serialized. The default option, SerializationMode.PlainText, simply serializes the object to a string and puts it inside of a hidden field. When using SerializationMode.Encrypted and/or SerializationMode.Signed, you are really using ASP.NET Webforms ViewState under the covers.

The call in your view source code is easy:

[code:c#]

<% using (Html.BeginForm()) {>
    <%Html.Serialize("person", Model); %>
    <fieldset>
        <legend>Edit person</legend>
        <p>
            <%=Html.DisplayFor(p => Model.FirstName)%>
        </p>
        <p>
            <%=Html.DisplayFor(p => Model.LastName)%>
        </p>
        <p>
            <label for="Email">Email:</label>
            <%= Html.TextBox("Email", Model.Email) %>
            <%= Html.ValidationMessage("Email", "*") %>
        </p>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
<% } %>

[/code]

When posting this form back to a controller action, a new ModelBinder can be used: The DeserializeAttribute can be placed next to an action method parameter:

[code:c#]

[HttpPost]
public ActionResult Edit([Deserialize]Person person, string Email)
{
    // ...
}

[/code]

There you go: Person is the same object as the one you serialized in your view. Combine this with the RenderAction feature (yes, check my previous blog post on the MVC futures), and you have a powerful model for creating something like controls, which still follows the model-view-controller pattern mostly.

Now release the hounds: I think this new “ViewState” feature is cool. There are definitely situations where you may want to use this, but… Will it be a best practice to use this? What is your opinion on this?

kick it on DotNetKicks.com

This is an imported post. It was imported from my old blog using an automated tool and may contain formatting errors and/or broken images.

Leave a Comment

avatar

11 responses

  1. Avatar for Dave Van den Eynde
    Dave Van den Eynde October 6th, 2009

    I think this could be helpful if JSON was one of the serialization option. That way, a page could already contain some data for a client script to work with, instead of having the client script perform a second request to get its initialization data.

  2. Avatar for Maarten
    Maarten October 6th, 2009

    Agreed. I've checked the internals, and this should be possible. It requires a lot of plumbing though... Will see if I can get in touch with the MVC team on that.

  3. Avatar for Haacked
    Haacked October 6th, 2009

    Just because Html.Serialized has the option of using Base64 encoding doesn't mean it equates to ViewState. I think calling it ViewState is very misleading First of all, what your serializing is the state of the Model, not the View. You just store it in the view. This helps with doing things like optimistic concurrency or wizards without having to store values in session or cookie.

    Also, unlike ViewState, this is opt in and not automatic and doesn't have any way of serializing the actual view.

  4. Avatar for David Kemp
    David Kemp October 7th, 2009

    This is so far from viewstate that it beggars belief.
    Since the dawn of time, people have been putting "state" in hidden form fields.
    MS took the mickey with their concept of viewstate to try to make WebForms behave like windows applications.
    However, having the ability to put an encrypted/signed ID value in a hidden field is really good, and can help security enormously.

  5. Avatar for PK
    PK October 7th, 2009

    I feel offended that it's possible the ViewState can come into the MVC framework. I know it has to be a manual thing, but i kept finding that the entire idea behind it was poor and poorly implimented. Yes, this is another geek-tech religious war, so I'm not going to fan the flames too much.

    Will i use it? nope.
    Will i recommend it? nope.
    Do i believe it could add some extra complexity to a project, despite it being added to reduce complexity or at least make things more RAD? (whoa, long sentence!): yes i do.

    I prefer to keep things simpler (KISS) -> its easy to read form data and not hard to time consuming to program that. The effort that has been abstracted away (eg. Deserialize attribute) i feel is minimal. It also worries me that there's sometimes too much black magic happening.

    Anyways, that's my opinion. it's neither right nor wrong.

    No viewstate for me in my MVC apps.

    but thank gawd for ASP.NET MVC :) totally changed the way we do our .NET development now! love it :)

    -PK-

  6. Avatar for maartenba
    maartenba October 7th, 2009

    Agreed, but I thought calling it ViewState would provide for some controverse :-)
    Working on a small proof-of-concept demonstrating this is actually a good addition.

  7. Avatar for Denny Ferrassoli
    Denny Ferrassoli October 8th, 2009

    Phew! I nearly choked on my sandwich after seeing "mvc:TextBox" and then coming to a header that says "ViewState!"....

    but after some reading I like the idea of an opt-in viewstate.

  8. Avatar for LOVE_MOSS_NOT
    LOVE_MOSS_NOT October 9th, 2009

    Viewstate??? Ufff... you got me really scared there for a sec. ViewState has its place, but I like my life without it so far...

  9. Avatar for John Farrell
    John Farrell October 9th, 2009

    @PK All this functionality is doing is serializing an object and then deserializing it back inside of a model binder.

    That is not complex, very KISS, and is certainly not anything close to "black magic". Is the Session[""] dictionary black magic?

  10. Avatar for Vijay santhanam
    Vijay santhanam October 10th, 2009

    As Phil Haack says in another thread, calling it ViewState is misleading as it's actually serializing a part of the model back to business logic.

    ViewState wasn't wrong, it was just a mess and hard to wield. The Serialize helper on the other hand is rather easy to deal with without getting out of hand.

  11. Avatar for PK
    PK October 25th, 2009

    @JohnFarrel and @Vijay :: yeah - so true. The more I thought about it after my post, the more I can to see that the word ViewState is a poor world for it, because that has some baggage from the WinForm's model.

    :)