LA.NET [EN]

ASP.NETArchive

Apr 02

The MVC framework: invoking actions asynchronously I

Posted in ASP.NET, MVC       Comments Off on The MVC framework: invoking actions asynchronously I

As we’ll see, the MVC futures assembly adds several classes which help you in executing asynchronous actions. In this post, we’ll take a quick look at the infrastructure code needed to start adding asynchronous actions to your controllers. As you’ll that it would be good to make a small incursion into the internals that support asynchronous requests in the MVC futures assembly. If ysee (when we’re done with this series), the futures assembly gives you several options to perform an action asynchronously. Before showing some code, I believe ou take a look at the MVC futures source code, you’ll see that it has several classes that start with or contain the Async word. Those classes are responsible for supporting the features we’ll be seeing in this and in the next posts.

Ok, nothing better than go back to the basics…as you recall, the routing module is really important and introduces the hooking point from where the MVC framework does its work. By default, when you register a route you end up using a helper method that associates a route with an instance of type MvcRouteHandler. As we’ve seen in the past, the only role of this route handler is to return the IHttpHandler that will process the request. Whenever you want to use asynchronous actions in your MVC app, you’ll need to associate a route with a different route handler: in this case, you’re interesting in using the MvcAsyncRouteHandler.

If you want,you can pass a reference to this route handler when you create a new Route object (I call this the manual – but more explicit! – approach). However,you’ll probably prefer the quickest option which consists in using the RouteCollection extension methods defined in the static AsyncRouteCollectionExtensions class. As you might expect, you’ll find several overloads which let you set several of the properties of the Route you’re creating.

The MvcAsyncRouteHandler is really similar to the existing MvcRouteHandler. However, in this case, it will return an instance of type MvcAsyncHandler that is responsible for handling the current request. This is an asynchronous handler (ie, it implements the IHttpAsyncHandler) and it also extends the MvcHandler class by adding a new property (SynchronizationContext) used internally for context propagation/synchronization (by default, it ends up using the default ASP.NET synchronization context).

The implementation of the BeginProcessRequest and EndProcessRequest methods are fairly simple. The BeginProcessRequest method will instantiate the correct controller (it uses our old friend ControllerBuilder to instantiate the requested controller) and see if it implements the IAsyncController interface. If it does, then it will handle the current request asynchronously. If it doesn’t then it will simply execute that request synchronously (by invoking the SynchronizationContext.Sync method). The IAsyncController is a simple interface which adds two new methods to the ones defined on the IController method:

public interface IAsyncController : IController { 
IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state);
void EndExecute(IAsyncResult asyncResult); 
}

There’s really not much to say about these methods…as you might expect, the BeginExecute method will kick off the asynchronous processing and the EndExecute will be called for cleaning everything up. The easiest way to implement this interface is to inherit from the AsyncController class. Again, this class builds on the existing Controller class and adds a very interesting property (which we’ll talk more about in the future): the AsyncManager property. This property (of type AsyncManager) can be used to register asynchronous tasks and we’ll return to this topic in future posts.

Internally, the class will end up using several other auxiliary classes that are responsible for setting up the scene and trying to understand which asynchronous pattern should be used for handling the current request. I’m tempted to say that the one of the most important pieces of work is performed by the AsyncActionMethodSelector. This class is responsible for deciphering the current pattern and creating the correct action descriptor that will be responsible for invoking the current method (it ends up delegating to the traditional ReflectedActionDescriptor when none of the current available patters are found).

In the previous paragraphs, I’ve mention several times asynchronous patterns. You’ll be happy to know that the current version of the future bits (at least the one I’ve downloaded to my machine) supports three different asynchronous patterns:

  • you can define two methods (BeginXXX and EndXXX) on your controller;
  • you can also expose two methods (XXX and XXXCompleted) that handle the beginning and ending of the processing (a similar approach to the async event pattern, but without events 🙂 );
  • finally, there’s a continuation pattern where you can return a delegate from the action method that gets things started.

Before ending, there’s still time for an additional note: if you’re using IIS 6, then don’t forget to add the following to your web.config file:

<add verb="*" path="*.mvc" validate="false" type="Microsoft.Web.Mvc.MvcHttpAsyncHandler, Microsoft.Web.Mvc"/>

I think this is getting rather big and I’ll postpone some samples for the next posts 🙂 Stay tuned for more on the ASP.NET MVC.

Apr 02

In these last days I’ve been busy with the source code of the futures assembly. I’ve already written one post (not published yet) and was planning on writing a couple more of them that showed how to use the asynchronous features introduced by the future bits. Well, it seems like my posts have just become redundant (though I’ll probably publish them anyway) because there’s a new document on codeplex which explains how to use it.

Mar 26

The MVC framework: the ContentTypeAttribute attribute

Posted in ASP.NET, MVC       Comments Off on The MVC framework: the ContentTypeAttribute attribute

Another short post on the features available on the MVC futures assembly…today, we’re going to take a look at the ContentTypeAttribute. This attribute is an action filter attribute and you can use it to setup the content type of the current response (ie, you can apply this attribute to an action method to influence the value of the ContentType property of the HttpResponseBase object). The constructor of the this type receives a string which identifies the content type of the response.

Internally, this action filter ends up overriding the OnResultExecuting and OnResultExecuted methods in order to set the HttpResponseBase’s ContentType property to the value you’ve passed to its constructor.

And that’s it. Keep tuned for more on the MVC…

Mar 25

The MVC framework: pay one take several

Posted in ASP.NET, MVC       Comments Off on The MVC framework: pay one take several

Ok, not really! It’s still free…today I didn’t really had the time to dig into the stuff I wanted to investigate. So, I’ll just present several interesting topics about the MVC futures assembly:

  • Binders: the MVC future has some offers in this area. Let’s start with the ByteArrayModelBinder. This binder will recover a byte array from an existing field (as you might expect, it will try to interpret the value as a base 64 string). Before using this binder, don’t forget to register it with the ModelBinders.Binders collection. There’s also a SkipBindingAttribute which you can use to skip binding on an action controller’s parameter;
  • Extensions: besides the extensions we’ve seen in the previous posts, there are a couple of other extensions which might be useful to you. Let’s start with the MailToExtensions. As you might expect from the name, these HtmlHelper method extensions let you add mailto links to your web views. There are several overloads which let you specify mail, subject, cc, bcc and body for the message. The ExpressionInputExtensions class adds several helpers which let you add textboxes, hidden fields, dropdowns,textareas and validation messages to a view. The main difference when compared to the ones present on the main MVC assembly is that these methods use Expressions for specifying the association between the generated field and a model property. If you’re looking for radio button helpers,then you’ll be pleased to know that the futures assembly has several helpers that might help you with that. RadioListExtensions is the class you want for this job. Items that are to be rendered should be passed through a collection of SelectListItem;
  • Caching: the futures assembly introduces a class (CacheExtensions) which lets you specify a method that should be called for rendering portions of the page that shouldn’t be cached. Internally, you’ll end up using the WriteSubstitution method of the HttpResponseBase class (which, in practice, means that you’ll end up calling that method over the HttpResponse class).

Since we still haven’t talked about using caching on MVC apps, I though this would be a good time for presenting a small example which illustrates the use to the CacheExtensions’ static methods. Lets suppose we’ve got a view which is cached. However, there’s a section which shouldn’t be cached, ie, there’s a specific portion of the view that should be regenerated for all the requests. Here’s how you might do that with this extension method (I’m just putting the view):

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ OutputCache VaryByParam="None" Duration="60" %>
<%@ Import Namespace="MVCRTM.Controllers"%>
<%@ Import Namespace="Microsoft.Web.Mvc"%>

<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">  
<form>
  <%= Html.SubmitButton( "Message", "hi" ) %>
</form>
<%= DateTime.Now %>

<% Html.Substitute(  ctx => DateTime.Now.ToString() );%>
</asp:Content>

Ok, this is just a really simple (and dumb!) view with a form whose sole objective is to force a refresh of the view. Without caching, you should see both times being refreshed. However, after adding the cache directive, you should notice that only the second date will be updated. Notice that the Substitute method expects a MvcSubsitutionCallback delegate, which looks like this:

public delegate string MvcSubstitutionCallback(HttpContextBase httpContext);

As you can see, you cam access the current context from within the method you’re passing to handle the substitution.

And that’s all for today. Keep tuned for more on the MVC framework.

Mar 24

Ok, here we are again for another episode on the inner workings of the MVC futures assembly. Today, we’re going to take a look at the HtmlHelper extension methods defined on the ViewExtension class. The current release of this class introduces two (static extension) methods which you can use to execute an action “in-place” during the current request:

  • RenderRoute: this method lets you pass a RouteValueDictionary which is added to a RouteData object. Then, the method uses an auxiliary handler to execute the new request “in-line”;
  • RenderAction/RenderAction<T>: there are several overloads of these methods. As you might expect, you’ll use them whenever you need to render a specific action of a controller. The main difference (when compared with the previous method) is that in this case you’ll end up getting two more entries on the RouteData’s Value dictionary: action and controller.

These methods end up delegating the execution of the request to a private handler: RenderActionMvcHandler. This handler expands the MvcHandler and the only thing it does is override AddVersionHeader so that it doesn’t set the custom HTTP version header. Ok, so it’s time to see this in action. Here’s a quick example that show how you can use it:

<% Html.RenderAction<HomeController>(c => c.Test()); %>

In this case, we’re rendering the Test action method of the HomeController “in-place” from within the view (yes, that call is made from within a view – not really good, right? more about it below). Do notice that the method tries to “emulate” a new request and things might not work for anything that falls out of the “simple staff” scenario. For instance, here’s a couple of things you should keep in mind if you intend to use this method:

  • it goes against the “spirit” of the pattern. Using this method means that you’re calling an action from a view (and in my opinion, that is not really a good thing);
  • the faked request might not have everything you might need. Since it doesn’t know (beforehand) what you need and what you want to replace you’ll get a predefined default behavior.

Ok, so now that you know that it has some short comes,you’re free to use it at your own risk :,)

And that’s all for today. Keep tuned for more on the MVC framework.

Mar 23

A few months back, we’ve seen how TempData is implemented and how it should be used. Today we’re going to keep looking at the future assembly and we’ll take a look at the CookieTempDataProvider class. The class implements the ITempDataProvider interface and you can use it it you intend to persist the temp data dictionary in cookies instead of relying in the traditional session temp data provider.

Internally, the class will serialize the data using the BinaryFormatter and encode it into a base 64 string which is then set as the value of a cookie which is added to the current response. Then, when the browser asks for a specific controller action and starts a subsequent request to the server, this temp data provider will search the request and see if there’s cookie with the previous persisted temp data dictionary (btw, it will search for a cookie named __ControllerTempData). If it finds one, it will rehydrate the temp data dictionary from that cookie’s value and then it will expire the cookie immediately. It will also search for an existing cookie on the response and will also invalidate it by clearing its content and expiring it (like it did to the one present on the request’s cookie collection).

The only thing you need to do is set the TempDataProvider that your controller class inherits from the Controller class. You have several options here. The important thing is that you shouldn’t set that value from the constructor of your controller because at that time your controller context is still null. A valid option could be overriding the Initialize method and set the TempDataProvider property:

protected override void Initialize(RequestContext requestContext){
  base.Initialize(requestContext);
  TempDataProvider = new CookieTempDataProvider( requestContext.HttpContext );
}

And that’s it for today! Stay tuned for more on the MVC framework.

Mar 22

The MVC framework: more on the future’s helpers

Posted in ASP.NET, MVC       Comments Off on The MVC framework: more on the future’s helpers

Ok, so in the previous posts I kept talking about some of the helpers available on the future assembly. In this short post we’re going to complement that information with some more methods that let you expressions for specifying form actions (yes, this can be seen as form extensions, part III).

The future assembly introduces 2 new extension methods with these signatures:

public static MvcForm BeginForm<TController>(this HtmlHelper helper, Expression<Action<TController>> action) where TController : Controller

public static MvcForm BeginForm<TController>(this HtmlHelper helper, Expression<Action<TController>> action, FormMethod method) where TController : Controller

As you can see, they’re really similar to the ones we have on the MVC assembly; the main difference, is that we’re using Lambdas for setting up the action that ends up deciding the url for the form’s submission. The use of this method follows the same approach we’ve seen for the button helper methods. And that’s it. There’s still more to come. Stay tuned!

Mar 22

Impressed with SuperPreview

Posted in ASP.NET, Tools       Comments Off on Impressed with SuperPreview

I”ve started watching MIX sessions and, until now, I can tell you that I’m really impressed with SuperPreview. I’ll be getting the expression tools just to see what it can be done with it (do keep in mind that there’s also a free version for IE).

Mar 22

Today we’re going to keep looking at other helps available on the future assembly. The topic for today is: ButtonBuilder and using the available extension methods for adding HTML button type elements to the page. We’re going to start looking at the functionalities available on the ButtonBuilder class (keep in mind that you won’t probably be calling these methods from the pages; generally, you’ll end up using the extension methods we’ll be presenting at the end of the post).

Currently, the ButtonBuilder (static) class exposes 3 (static) methods:

  • SubmitButton: used for inserting a <input type=”submit”> element to a form;
  • SubmitImage: used for generating a <input type=”image”> element on a page;
  • Button: used for adding <button> elements to a page.

Here’s a quick example of how you might use the Button method to add a <button> element and to configure it so that it shows an alert message when someone clicks on that button:

<%= Html.Button( "message", 
                             "H", 
                             HtmlButtonType.Button, 
                             "printHello()") %>

As you can see, we’re using one of the HtmlHelper extension methods defined on the ButtonsAndLinkExtensions static class. Besides this method (and its overloads), the class exposes also several other methods that redirect to the methods presented on the previous list.

One of the things you should keep in mind is that, in this case, the name parameter is used only to set up the HTML name (or id) attributes on the generated HTML control. So, if you need to pass a value from the view data dictionary, you’ll have to do it explicitly.

And that’s it. There’s still more to say about the MVC framework,but I’ll leave it to another day…

Mar 21

Ok, now that codeplex is up again, I’ve already downloaded the latest bits for the ASP.NET MVC framework. In the past, we’ve already seen that there are several helpers for generating links for specific actions. As we’re going to see today, the future assemblies adds more ActionLink extension method helpers that let you specify the url of an anchor in a strongly typed manner (by using Expression<T> to define the associated action instead of relying on strings).

As you might expect, the first thing we need to do is add a reference to the future assembly in our MVC project. Then, we’ll start by adding a reference to the Microsoft.Web.Mvc namespace on the view by using the Import directive:

<%@ Import Namespace="Microsoft.Web.Mvc" %>

Now, we can start using the new ActionLink extension in the page. Here’s a quick example (supposing we’ve got a ShowMessage action method on the HomeController class that receives a string parameter called msg):

<%= Html.ActionLink<HomeController>(
                             c =>c.ShowMessage(“hi”), “Say hi!” );

As you can see, we’re passing  an Action<T> expression (where T is a controller) which ends up being parsed and transformed into a RouteValueDictionary. In this case, we’re passing a constant value to the ShowMessage. When the expression isn’t a constant, it ends up being converted into a compiled Lambda Func<Object> which is invoked. btw,here’s the HTML generated by the previous snippet:

<a href=”/Home/ShowMessage?msg=hi”>Say hi!</a>

And that’s it: by using this helper,you can build your anchors’ url in a strongly typed way. btw, and since we’re talking about additional link features introduced by the futures assembly, this post wouldn’t be complete without mentioning the BuildUrlFromExtension<T> method (an HtmlHelper extension method). The main difference (when compared with the previous method) is that this method will only return the url (instead of the complete HTML for the anchor).

And that’s it for today. Keep tuned for more on the MVC framework.

Mar 17

Today we’re going to keep looking at the futures assembly. In a previous post, we’ve seen how we can easily return a file from an action method. Today, we’re going to take a look at how we can use the FileCollectionModelBinder to get access to a group of files that have been uploaded to the server. The first thing you need to do when you want to use this binder is to register it. The FileCollectionModelBinder introduces a static method that registers the binder for all types of collections off HttpPostFileBase items. We can do this from within application start event:

protected void Application_Start() {
   RegisterRoutes(RouteTable.Routes);
   FileCollectionModelBinder.RegisterBinder( ModelBinders.Binders );
}

After doing this, all parameters of type HttpPostedFileBase[], IEnumerable<HttpPostedFileBase>, ICollection<HttpPostedFileBase>, IList<HttpPostedFileBase>, Collection<HttpPostedFileBase> and List<HttpPostedFileBase> will be automatically filled by this custom binder. In order to illustrate its use, we’ll start by adding a form to a view that lets you update files. Here’s the markup we’re using:

<% using( var form = Html.BeginForm(
                                         "ProcessFiles",
                                         "Home",
                                         FormMethod.Post,
                                         new { enctype = "multipart/form-data"}))
{%>
    <input type="file" name="files" />
    <input type="file" name="files" />
    <input type="file" name="files" />
    <input type="file" name="files" />
    <input type="submit" value="Send files" />
<% }%>

As you can see,we need to add the enctype attribute “by hand” to the form tag. If you don’t do that,you’ll end up without no files on the server side. Another interesting thing is that we’re defining several <input type=”file”> elements and we’re giving them the same name. We’re doing this because we want to get them all on the server side. Here’s the code for the ProcessFiles method:

public ActionResult ProcessFiles(IEnumerable<HttpPostedFileBase> files) {
  //do something with the files here
  return GetView();
}

If everything works out, files will give a collection with all the files submitted by the user on the browser. It’s important to keep in mind the rules associated with the binding associations: the parameter name must match the name of the files you want to retrieve form the form (in other words, make sure that the parameter name matches the name attribute you’ve passed to the input elements of type file you want to recover). I haven’t tested it, but this should also work with custom objects with properties that match one of the types handled by this binder.

And that’s all for today. Keep tuned for more on MVC.

Mar 16

Today we’re going to look at the last available control on the futures assembly: we’re talking about the Repeater control. If you’ve dealt with web forms server controls in the past, then looking at the code of the Repeater class shouldn’t make you have any “haha moment”. As you might expect, the class expands the MvcControl class and adds a couple of properties to it:

  • ItemTemplate: property of type ITemplate which lets you specify a template that should be applied to all the items;
  • EmptyDataTemplate: lets you sepcify an ITemplate instance that will be rendered when there aren’t any items to render;
  • Name: used for trying to get the collection of items from the view data dictionary that could have been passed to the view.

This class doesn’t really do much in the Render method. It will only try to get an IEnumerable instance from the view data dictionary (by using the Name property as the key) and if it finds data, it will  instantiate its ItemTemplate for each item of the collection. As you might have guessed, when there’s no data, the class will only render the stuff you’ve specified on the EmptyDataTemplate property.

Since we’re looking at the internals, our study wouldn’t be complete without mentioning the RepeaterItem class. This is a simple wrapper class which expands the Control base class and implements the IDataItemContainer and IViewDataContainer interfaces. When you pass a valid collection on the view data dictionary, the Repeater control will instantiate an instance of this type for each existing item on that collection. And that’s all you need to know about the internals. Lets see how we can use this in a web form view…

We’ll start by creating a new collection which is going to be passed to the view. Notice that we can even get away with anonymous objects (which is great for demo code like this):

var collection = new[] {
                                         new {
                                                     Id = 1,
                                                     UserName = "Luis"
                                             },
                                         new {
                                                     Id = 2,
                                                     UserName = "Paulo"
                                             },
                                         new {
                                                     Id = 3,
                                                     UserName = "Jose"
                                             }
                                 };
ViewData["repeaterItems"] = collection;

Now,we only need to setup the repeater. In this code, we’ll only use some simple MVC labels for showing the output:

<mvc:Repeater runat="server" Name="repeaterItems">
     <ItemTemplate>
       <div>
         Id: <mvc:Label runat="server" Name="Id" /><br />
         Name: <mvc:Label runat="server" Name="UserName" /> <br />
      </div>
     </ItemTemplate>
</mvc:Repeater>

And that’s it. If you load the page you should see a list of users passed from the view. Do keep in mind that the “old” binding expressions still work. For instance, you could have used these expressions for getting the same info from the collection:

<%# Eval("Id") %> – <%# Eval("UserName") %>

You can even do more complicated things…For instance, you can render collections of collections, like Eilon shows in this post.

One of the things you will not get in the  current release is the ability to specify an alternating template in markup. For instance, lets say that you wished to specify a different css class for the container div used inside the ItemTemplate of the repeater. You’ll have to write some simple code to make that happen. Here’s an example of how you could do that:

<mvc:Repeater runat="server" Name="repeaterItems" ID="myRepeater">
      <ItemTemplate>
       <div class="<%# GetCss(Container) %>">

As you can see, we can still use our old good *Container* to get a reference to the RepeaterItem instance that is being used for the rendering. Then, we could prob
ably write code like this to get the correct css:

protected String GetCss(object obj) {
      var item = obj as Microsoft.Web.Mvc.Controls.RepeaterItem;
      return ( item.DataItemIndex%2  )== 0 ? "even" : "odd";
}

I say *probably* because the truth is that you can’t. The reason is simple: there’s a bug on the rendering logic and the RepeaterItem is always initialized with index 0. It’s simply to solve this: just increment the index counter and recompile the code.

And I believe there’s not much to talk about on the MVC controls available on the future assembly. We should be getting more stuff when the final version of MVC is out, but the truth is that for now there really isn’t much more than can be said about these controls. On the other hand, there are still lots of stuff to talk about on the MVC futures assembly! So, keep tuned if you want to read more about MVC.

Mar 12

The MVC framework: the DropDownList control

Posted in ASP.NET, MVC       Comments Off on The MVC framework: the DropDownList control

Today we’re going to keep looking at the futures assembly and we’ll take a peek at the DropDownList control. Currently, the class exposes the following properties:

  • Name: used to identify the control and recover the collection of SelectListitems that might have been added to the view data dictionary;
  • OptionLabel: used for passing the text that is set up as the top option show to the user by default.

As you might expect, the rendering is really similar to what happens in the TextBox: the difference is that in this case you’ll end up having several OPTION elements rendered. If you look at the code, you’ll notice that this is still work in progress (and that’s why it’s still on the futures assembly!): you can only generate DropDownLists but it seems like in the future we’ll have an intermediary class for holding common code and then two specialized classes for rendering DropDownList and ListBoxes. That’s the only reason I can  think of for having code that can generates dropdowns or listboxes and that is always hard coded for generating dropdowns…

Ok, so let’s see how we can use this control to add a drop down to a view. We’ll start with the markup:

<mvc:DropDownList runat="server"
      name="myDrop"
      optionlabel="choose an option" />

Now, we need to ensure that there’s an entry in the view data dictionary with the name myDrop which has a collection of items. Since this is demo code, I’ll just add these lines to the action method that returns the view that contains the markup presented in the previous snippet:

var items = new[]{
                               new SelectListItem
                                   {
                                           Text = "Option 1",
                                           Value = "Opt1"
                                   },
                               new SelectListItem
                                   {
                                           Text = "Option 2",
                                           Value = "Opt2"
                                   }
                       } ;
ViewData["myDrop"] = items;

And that’s all you need to fill the dropdown. btw, don’t forget that you can use the SelectList class for passing a custom collection of items like it was shown here. And that’s all for  today. Keep tuned for more about MVC.

Mar 11

The MVC framework: more on the MvcInputControl

Posted in ASP.NET, MVC       Comments Off on The MVC framework: more on the MvcInputControl

Oh well…after all, the MvcInputControl is more complex than I initially thought. The problem was that I was using SVN for getting the code and it seems like the current available release is for that kind of access is still RC1. Fortunately, you can still download the source from codeplex and that is what I did. So, the current release (RC2) adds a property to the previous list: Format. As you can probably guess, you can use this property to specify the format that should be applied to the value that is rendered by the INPUT control.

Besides this property, the class adds further logic to the rendering method. In this version, the INPUT control’s value can come from several places, by this order:

  1. it tries to get an attempted value from the associated ModelState (it uses the Name property to try to get a valid ModelState entry). If it gets one, then it will simply set it as the value of the INPUT control and it won’t apply any kind of formatting to it (even if you set up a value to the Format property, it won’t be applied);
  2. It then tries to get a value from the attributes you’ve set up on the markup;
  3. If that doesn’t return a valid value, it will try to get that info from the view data dictionary.

If the it gets a value from 2 or 3 and the Format property was set up, it will apply that form to the string before adding it to the rendered attributes. Finally,it performs a final step: it checks for eventual errors on the associated ModelState (again,remember that it uses the Name property for getting that info from the view data dictionary). If it finds any, it will automatically add the default validation css class (HtmlHelper.ValidationInputCssClassName) to the control. And now I believe the MvcInputControl has been accurately described.

Keep tuned for more on the MVC framwork.

Mar 11

As you might expect (from the title), this is another post on the MVC controls series. Today we’ll be looking at the MvcInputControl class which is responsible for rendering the text input controls. As you might expect, this class expands the MvcControl class and it exposes only one constructor which receives the type of text input you want to generate (as we’ll see, the current release supports only simple, password and hidden text controls). This parameter ends up initializing the InputType property. The class does exposes another property, Name, which is used in the same way that you saw in the Label post.

Besides these two properties, the class is also responsible for rendering the HTML. it does that by overriding the Render method and using it to output the corresponding HTML INPUT element. The rendering process involves:

  • going through all the attributes and adding them to the current element that is going to be outputted;
  • add the correct INPUT type by checking the InputType property;
  • add the name and id attributes. These are set to the Name property if you don’t explicitly pass a value to those attributes on the markup;
  • the INPUT value’s is added to the output, whenever possible. The algorithm used is based on the one presented for the Label control. Basically, whenever it can, it gets the value from the  view data dictionary that gets passed in.

And that’s it. Currently, this wrapper doesn’t do anything else. Whenever you need a text control,you must use one of the derived classes: TextBox,Hidden or Password. This classes are only there to introduce a default constructor which is responsible for extending the MvcInputControl class and for passing the correct type to the base constructor. For instance, here’s what you have for the TextBox control:

public class TextBox : MvcInputControl {
       public TextBox() :
           base("text") {
       }
}

If we reuse the previous example, then we the following snippet will produce a textbox with its value set to whatever exists in the view data dictionary with that key:

<mvc:TextBox runat=”server” name=”Message” />

And here’s the HTML I’m getting on my browser:

<input name="message" id="message" type="text" name="message" id="message" value="hi there! This is aa label" />

And that’s it for today…more about MVC on the next posts.

Mar 10

Protected: The MVC framework: the Label control

Posted in ASP.NET, MVC       Comments Off on Protected: The MVC framework: the Label control

This content is password protected. To view it please enter your password below:

Mar 09

The MVC framework: getting started with the MVC controls

Posted in ASP.NET, MVC       Comments Off on The MVC framework: getting started with the MVC controls

Ok, you’ve probably read Eilon’s post on the new MVC controls. I was asking for something like that when I mentioned that I dind’t think that codebehind files were evil. So, I thought it would be great to take a look at what’s available for the current release (even though the controls are still on the futures assembly).Today, we’re going to start by looking at the basics: the MvcControl class.

At first look, this class is supposed to be used as the base of all MVC server controls. The class adds several interesting properties related with MVC:

  • ViewContext: this property goes through the complete control hierarchy until it reaches a valid view (ie, an element of type ViewPage). After that, it simply reaches to the ViewPage’s ViewContext property and caches it in an internal field;
  • ViewDataContainer: this is a property of type IViewDataContainer. In practice, this property will return a reference to the ViewPage or ViewUserControl where the MVC control is defined;
  • ViewData: shortcut for the view data dictionary associated to the current view;

As you’ll see, the other more specialized classes will reuse this info to render the correct HTML (but that’s a story to another post). The class also implements the IAttributeAccessor interface so that it can keep track of the attributes that are defined on the markup (you should do this if you don’t want to map the attributes to properties exposed by the class – like happens in this case). Besides that, the class also overrides the EnableViewState property. It does that in order to hide it from the designer and from the property editor. Unfortunately, it didn’t go as far as it should. In my opinion, it should override the getter and always return false and do nothing on the setter (or throw an exception if true was passed to it). I still have doubts about reusing the Control class,but I guess that it was done for reusing all the parsing logic that exists on the ASP.NET Web Form world.

And that’s it for this post. On the next,we’ll start looking at

Mar 08

Posts for the next days

Posted in ASP.NET, MVC       Comments Off on Posts for the next days

This should keep me occupied for some time…

Mar 07

Update: Andre pointed out that I shouldn’t be calling this a postback because this isn’t posting any data back to the server. And yes, he’s right. Oh well, now it’s too late to change the title so I’ll leave it just like that. So, if you’re reading this, keep in mind that in this post postback should be read as async request to the server]

Today we’re going to take a look at the last interesting feature which is available on the AJAX MVC helpers: running a partial postback by clicking on a hyperlink. The idea is to add an anchor to a page and configure it so that a click starts a partial postback to the server. To make things a little bit interesting, we’re going to return a JSON response and we’re going to handle it on the complete method that fires up on the client side (by doing this, we’ll be seeing another available option to the traditional one where you return HTML and rely on the client MS AJAX framework for updating the HTML).

As you might expect, you can easily add the anchor that will make all this happen through several server (extension) methods (overloads) available on the AjaxHelper class. In the next snippet, we’re using one of the overloads of the ActionLink method to insert the anchor that performs the partial postback request on the view:

<%
    var options2 = new AjaxOptions{
      OnComplete = "handleComplete",
    };
    %>
<%= Ajax.ActionLink("AJAX link", "HandleAjaxLink" , options2)%>

As you can see,we need to specify the AJAX options by passing an instance of type AjaxOptions. In this case,we’re only specifying the JS method that should be called when the response is returned from the server. Since we’ll be doing everything on that method, we don’t need to specify anything else.

When the previous view is rendered, you’ll end up with the following HTML:

<a href="Home/HandleAjaxLink" onclick="Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, httpMethod: ”POST”, loadingElementId: ”info”, onComplete: Function.createDelegate(this, handleComplete) });">AJAX link</a>

This is really similar to what you get when you use an “AJAX form”. The main difference is that you’ll end up getting no payload for the request. Everything else we’ve said about the life cycle of the request associated to an “AJAX form” is also true for this kind of postback, so we’re not going to repeat it here. Going back to the example, we’re just returning some simple JSON from the server method:

public ActionResult HandleAjaxLink() {
  var user = new { Id = 1, Name = "Luis"};
  return Json(user);
}

And now we’re ready to intercept the response returned on  the client side (notice that we’re using the handleComplete JS method for handling the OnComplete event on the client side – notice that we do this on the AjaxOptions object that is passed to the ActionLink method). Here’s the JS code I’ve written for it:

function handleComplete(context) {
  var a = Sys.Serialization.JavaScriptSerializer.deserialize(
                                                                   context.get_data() );
  alert(a.Id + "-" + a.Name);
  if (context.get_loadingElement()) {
    Sys.UI.DomElement.setVisible(context.get_loadingElement(), false);
  }
  return false;
}

As you can see, we’re reusing the JavaScriptSerializer to recover the returned JSON response (read this to understand why). After that, we’re just showing the returned info through an alert message. Then, there’s something which we need to remember to do: hide the loading element if we’re using one. Notice that you’ll only need to do this if you’re intercepting the normal processing of the response on the client side (like we’re doing here by returning false from the method). In my opinion, this should be done by the framework, but the truth is that it’s not…).

And that’s all for today. Keep tuned for more on MVC framework.

Mar 04

The MVC framework: More on AJAX

Posted in ASP.NET, MVC       Comments Off on The MVC framework: More on AJAX

The last example we’ve looked at showed how we can add AJAX to a MVC app. However, that example probably needs some more work: after all, we also want it to work when the user has Javascript disabled on the browser. The current version isn’t really that far from achieving that objective. Currently, when JS is disabled, you’ll end up having a full postback to the URL specified in the form’s action. Since that is also being used for the AJAX request, then we already have a common action that will be used in both cases: we just need to adapt the server code (notice that you could also use the Url property of the AjaxOptions object to have 2 different urls for each kind of request).

Here’s the current code for the HandleAjaxUpdate method:

public ActionResult HandleAjaxUpdate(User user) {
  Thread.Sleep(2000); //sleeping for seeing message
  ValidateUserId(user); 
  ValidateName(user); 
  return ModelState.IsValid ? 
         View(“Infosaved”) : View("myform", user);
}

See the problem? When we have an AJAX request, everything works as expected and we’re just returning the partial view. But this is not what we want when we have a full postback. If  we could know if the current request uses AJAX, then everything would be really simple: if it uses AJAX, then return the partial view; if not, just return the complete view.

The good news is that you can see if the current request is an AJAX request: just call the Request.IsAjaxRequest (extension) method. It returns true when you’re in an AJAX request (btw, this method returns true when the current request has a X-Requested-With header with the value set to XMLHttpRequest or when there’s a field with that name and value on the current form’s collection). Here’s a solution that might work for this example:

public ActionResult HandleAjaxUpdate(User user) {
  ValidateUserId(user); 
  ValidateName(user); 
  return ModelState.IsValid ?
               (ActionResult)RedirectToAction("PrintInfo")
                     :
               GetAdequateViewForCurrentRequest(user);
}

private ActionResult GetAdequateViewForCurrentRequest(User user) {
  return Request.IsAjaxRequest() ?
                                 View("myform",user) : View("Index",user); 
}

In this case, I’ve opted for redirecting the user into the PrintInfo action when there aren’t any errors there (you could even use TempData if you need to pass info from the current action). When there are errors, we use the IsAjaxRequest method to check if we’re handling an AJAX request. If we are, then we only need to return the partial view (same thing as we saw in the original post); when that doesn’t happen, we need to return a complete view.

To make everything work, we can transform the view into a typed view:

<%@ Page Language="C#"
                MasterPageFile="~/Views/Shared/Site.Master"
                Inherits="System.Web.Mvc.ViewPage<User>" %>

And we also need to make a slight change on the way the partial view is rendered from within the index view:

<% Html.RenderPartial("myform", Model); %>

And that’s it: with a couple of simple changes you have an app which uses AJAX and falls back to a traditional full postback model when there isn’t any JS support on the browser.

And that’s all for today. Keep tuned for more on the MVC framework.

Mar 04

Yesterday we’ve seen an example that shows how you can easily add “partial postbacks” to an MVC app. Today, we’re going to take a deep dive on the client AJAX MVC API that is used to perform all the communication with the server side. As you recall, we must use an AJAX form  to get that “partial postback” behavior. As I said at the time, this is a simple post which injects some JS code for intercepting the submitting event and performing an out of band call to the server side. Lets recall the C# code used for creating the form:

<%
    var options = new AjaxOptions{
      HttpMethod = "GET",
      UpdateTargetId = "holder",
      LoadingElementId = "info",
      Confirm = "Are you sure you want to try to update this user?",
      InsertionMode = InsertionMode.Replace,
      OnBegin = "handleBegin",
      OnComplete = "handleComplete",
      OnFailure = "handleFailure",
      OnSuccess = "handleSuccess"
    };
    using( var ajaxForm = Ajax.BeginForm( "HandleAjaxUpdate",options ) )
    {
  %> 
    <!—OTHER CODE REMOVED –>
  <%}%>

If you peek on the source,you’ll see that you end up getting the following HTML:

<form action="Home/HandleAjaxUpdate" method="post"
         onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, confirm: ”Are you sure you want to try to update this user?”, httpMethod: ”GET”, loadingElementId: ”info”, updateTargetId: ”holder”, onBegin: Function.createDelegate(this, handleBegin), onComplete: Function.createDelegate(this, handleComplete), onFailure: Function.createDelegate(this, handleFailure), onSuccess: Function.createDelegate(this, handleSuccess) });"> 
  <!—OTHER FIELDS REMOVED –>
</form>

As you can see, the onsubmit event is handled by the Sys.Mvc.AsynForm.handleSubmit method. Most of the info you set up on the server with the AjaxOptions instance is converted into a JS object that looks like this (formatting the previous code for better reading):

{
  insertionMode: Sys.Mvc.InsertionMode.replace, 
  confirm: ”Are you sure you want to try to update this user?”,
  httpMethod: ”GET”,
  loadingElementId: ”info”, 
  updateTargetId: ”holder”,
  onBegin: Function.createDelegate(this, handleBegin),
  onComplete: Function.createDelegate(this, handleComplete),
  onFailure: Function.createDelegate(this, handleFailure),
  onSuccess: Function.createDelegate(this, handleSuccess)
}

The only new thing going on here is that “client delegates” are created for the methods you’ve passed to the OnXXX properties. The Sys.Mvc.AsynForm.handleSubmit method is really simple: it will just serialize the fields of the form and use the internal _asyncRequest method for initiating the out of band call with the server. This method ends up performing several steps:

  • it checks the property confirm to see if you’ve passed a confirmation message that should be shown to the user;
  • tries to get the HTTP method from the anonymous JS object that was built from the info injected on the page. If you don’t set this property, you’ll end up using the HTTP  method defined by the method attribute of the HTML form element that is being submitted;
  • finds the URL that is going to be used to perform the remote call. If you don’t pass any on the AjaxOptions you’ve used on the server side, then you’ll end up with the action attribute of the current form. Notice that when you use GET, you’ll also get the body payload appended to the url (keep this in mind because there’s a size limit for an URL);
  • it creates and initializes the Sys.New.WebRequest object used for communicating with the server side. All the necessary configurations are performed here: the URL, body and HTTP verbs of the request object are configured and the headers are updated to reflect the current request;
  • it checks for the existence of a loading element (loadingElementId on the anonymous JS object that is inserted on the page). If it finds one, it will make it visible;
  • if you’ve specified a function for the onBegin property, that function will be called and it will be passed a reference to the current context (object of type Sys.Mvc.AjaxContext). If you return false, you stop the async postback;
  • it sets the request object’s callback method to another internal method that will do the remaining work when a response from the server arrives;
  • finally, it dispatches a call to the action method on the server side.

The “current context” is important and is represented by an instance of the Sys.Mvc.AjaxContext class. this class exposes “properties” which replicate most of the info that was injected on the page through the anonymous JS object. You’ll receive an instance of this type in the methods that you’ve  hooked up for the OnXXX properties. Here’s a list of available “properties”:

  • insertionMode: used for getting the insertion mode;
  • loadingElement: references the DOM element identified by the LoadingElementId property of the AjaxOptions object used on the server side;
  • response: reference to the response object returned from the server (only set after the response hsa been received);
  • request: reference to the request object used to perform the out of band call;
  • updateTarget: reference the element whose contents should be updated when the call completes and returns valid HTML.

As I’ve said, the response from the server is handled by an internal callback method defined by the platform (Sys.Mvc.MvcHelpers._onComplete if you’re curious). This is where most of the methods you specified for the OnXXX are executed and where the contents of the page are updated. here’s what happens in this method:

  • the response object of the current “AJAX context” is updated. Now, you can use it to get more info about the response sent from the server;
  • the onComplete method (if you specified one) is called. If you return false, the processing ends here;
  • If you’ve got a success code, the contents of the payload are evaluated. If you’ve returned JS from the server side (specified by setting the application/x-javascript content type header), that JS code is evaluated; on the other hand, if you’ve returned HTML, it will get appended to the specified target element using the insertion mode you’ve specified. If everything goes ok, the onSuccess method (when specified) will be called;
  • if you didn’t get a success code (that is, if the  code wasn’t in the 200-300 range, excluding the  1223 error codes), your onFailure method will be called (if you specified one);
  • if you’ve set up a loading element, it will be hidden.

And that’s all that happens in the client side when you use an “AJAX form”. Do keep in mind that if you return 304, you’ll only get the onSuccess method (nothing will be done on the response data returned – for starters,
it shouldn’t really be anything there). Another thing to remember is that all the calls go through the Network infrastructure of the client ASP.NET AJAX platform. This means that besides the hookups presented (the OnXXX methods you can specify in the AjaxOptions object), there are still others available by default by the client framework.

And that’s it for today. Keep tuned form more on ASP.NET MVC.

Mar 03

The MVC framework: adding AJAX to your app

Posted in ASP.NET, MVC       Comments Off on The MVC framework: adding AJAX to your app

In the last post we’ve already seen one way to add AJAX to an MVC app: using the AJAX JQuery methods in order to get a JsonResult from the server. In this post we’re going to take a look an another approach: using the MVC AJAX helpers (which are based on the MS client AJAX API) for submitting all the forms’ fields and refreshing a specific zone on the page (ok, if you know ASP.NET AJAX, you can say that this is "”AJAX a la UpdatePanel” :),,). Before going on, you should keep in mind that I do prefer to use the previous approach where the data are returned from the server and the UI is built on the client side. However, this other approach might also be a valid in some scenarios (and I’ve noticed that many people do prefer it over the other option). After this short intro, it’s time to start writing code…

To illustrate how everything work, we’ll suppose that we want to perform the update of the info introduced on a form without a postback.  To achieve this, we’ll start by creating a new class that will be used by the default binder to recover the info submitted by the form:

public class User {
  public Int32 UserId { get; set; }
  public String Name { get; set; }
}

Now, we can start thinking about the way we’re going to ajaxify the form. In this case, we’ll be replacing the form’s content with the HTML that is returned from the server side. To achieve that, we’ll start by creating a partial view which will only generate the form’s fields. I’m going to call it myform:

<%@ Import Namespace="MVCRC.Controllers"%>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<User>" %>
<label id="userIdLabel" for="userid">User id:</label>
<%= Html.TextBox( "userid") %>
<%= Html.ValidationMessage( "userid") %>
<br />
<label id="nameLabel" for="username">Name:</label>
<%= Html.TextBox( "name") %>
<%= Html.ValidationMessage( "name") %>
<br />
<input type="submit" value="Change info" />
<br />
<%= Html.ValidationSummary() %>
<p />
<small>Last update: <%= DateTime.Now %></small>

As you can see, the partial view contains only the fields (and validators) required for presenting the user and allowing its edition. It’s important to notice that the HTML form element isn’t rendered in the partial view. Since we’re at it, I think that it’s good time to mention that, in this case, we’ll need to use an “AJAX Form” (a term I‘ve just made up:) – I hope I’m not breaking any copyright) . An “AJAX form” is an HTML form which injects JS code that intercepts its submission and starts a partial postback (instead of the traditional full postback). We’ll be talking more about this code when we look at the client infrastructure. Generating an “AJAX form” is easy: just invoke the BeginAjaxForm (extension) method available on the AjaxHelper class.

Until now, I hadn’t mentioned this class (it introduces further methods, which we’ll leave for a future post). For today, we’re only going to take a look at the BeginForm method. As you might expect, you have several overloads of this method that you can use to have complete control over the url that will be used for posting data back to the server. We’ve already talked about these parameters when we saw how to generate traditional forms, so we’re not looking at them here again.

However, we do need to talk about a new parameter that these methods introduce (when compared with the helpers that generate traditional forms). I’m talking about the ajaxOptions parameter (of type AjaxOptions) which is used for setting several properties which are reused by the client infrastructure. In the current version, you can set the following properties:

  • Confirm: string which presents a message (window.confirm) that is shown to the user before the AJAX call is made. If you don’t set this property, the confirm window won’t be shown;
  • HttpMethod: user for setting the HTTP method that is going to be used by the AJAX call. Notice that you must specify a string, not a value from an enumeration;
  • InsertionMode: a value from the InsertionMode which decides how the HTML returned from the AJAX call is inserted on the page;
  • LoadingElementId: the client ID of an element which is shown during the AJAX call. You can use this to specify the ID of an HTML element that shows some sort of progress bar during the partial postback;
  • OnBegin: name of a method that is called at the beginning of the partial postback on the client side. You can return false from this method if you which to stop the current AJAX request;
  • OnComplete: lets you pass the name of a method that will be called when the response arrives from the server. Returning false from this method cancels the rest of the default client processing;
  • OnFailure: you can pass the name of a method that will be called whenever you get an error status on the response (excluding 304 and 1223);
  • OnSuccess: lets you indicate the name of a method that will be called after the payload is loaded and the HTML of the page is updated;
  • UpdateTargetId: string which identifies the client ID of the container that should be updated with the HTML returned from the server;
  • Url: you can use this property to specify the url to which the AJAX call should be made. If you don’t pass a value to this property, the form’s action attribute is used instead.

Before showing the code of the view, I’d also like to add is that there’s also a BeginRouteForm that lets you specify the url in terms of routes. Now, we’re ready to take a look at the code of the view:

<%
    var options = new AjaxOptions{
      HttpMethod = "GET",
      UpdateTargetId = "holder",
      LoadingElementId = "info",
      Confirm = "Are you sure you want to try to update this user?",
      InsertionMode = InsertionMode.Replace,
      OnBegin = "handleBegin",
      OnComplete = "handleComplete",
      OnFailure = "handleFailure",
      OnSuccess = "handleSuccess"
    };
    using( var ajaxForm = Ajax.BeginForm( "HandleAjaxUpdate", options ) )
    {
  %>
    <div id="holder">
     <% Html.RenderPartial("myform"); %>
     </div>
  <%}%>
  <div id="info" style="visibility:hidden">Trying to update…</div>

Since this is just demo code, I’ve decided to set as many properties as I could 🙂 Lets start with the AjaxOptions instance. We’re saying that we’re making a GET request and the target whose contents should be updated is the #holder element (the div that is placed inside the form). We’re
also specifying the loading element. In the previous example, we’ll be showing a div which contains a simple message. Do notice that you need to hide it on the initial display because you’re only interested in seeing it during the partial postback. The confirm message (notice that the Confirm property is set) will be show whenever the users submits the form.

We’ve also passed strings that identify all the client methods that can be called, though we won’t be doing any work on them (if you’re copying the code, you can add breakpoints and see what going on at each moment).

As we’ve seen, we need to use the BeginForm method to generate the form. In this case, we’re redirecting the form to the HandleAjaxUpdate method (which we’ll take a look at in a few moments). Before that, lets take a look at the signatures of the client methods:

<script type="text/javascript">
    function handleBegin(context) {
      printInfo(context);
    }

    function handleComplete(context) {
      printInfo(context);
    }

    function handleFailure(context) {
      printInfo(context);
    }

    function handleSuccess(context) {
      printInfo(context);
    }

    function printInfo(context) {
      var info = ["insertion mode:", context.get_insertionMode(), "-",
                  "loading id; ", context.get_loadingElement().id, "_",
                  "target id; ", context.get_updateTarget().id];
      alert(info.join(""));
    }
</script>

AS you can see, they’re really similar: all of them receive an instance of the client Sys.Mvc.AjaxContext class. This class exposes several properties which let you access the current request object, the update target element, the loading element, etc. We’ll come back to this class in a future post when we take a deep dive at the client infrastructure. There’s still an important detail that needs to be done to conclude the work in the view: we need to add the script references to the client AJAX files. Here’s how you can do that:

<script src=”<%=Url.Content( "~/Scripts/MicrosoftAjax.debug.js") %>” type="text/javascript"></script>
<script src=”<%=Url.Content( "~/Scripts/MicrosoftMvcAjax.debug.js") %>” type="text/javascript"></script>

Now it’s time to take a quick peek at the server HandleAjaxUpdate method:

public ActionResult HandleAjaxUpdate(User user) {
  Thread.Sleep(2000); //sleeping for seeing message
  ValidateUserId(user); 
  ValidateName(user); 
  return ModelState.IsValid ? 
         View(“Infosaved”) : View("myform", user);

private void ValidateName(User user) {
  if (String.IsNullOrEmpty(user.Name)) {
     ModelState.AddModelError("name", "Name cannot be empty");
  }

private void ValidateUserId(User user) {
  if (user.UserId < 0) {
   ModelState.AddModelError("userid",
                         ser Id must be a positive number");
  }
}

As you can see, we’ve got similar code to the one I’ve in several of the previous posts. The main difference here is that when there’s an error, we simply return the partial view (which is strongly typed and is automatically filled from the current info available on the action method). WHen everything is ok, we return a view which gives that message to the user.

And that’s it: with these simple steps you know have “partial postbacks a la UpdatePanel”. There’s still more to say about AJAX in MVC but I’ll leave that for the next posts. Keep tuned!

Mar 03

The MVC framework: returning JSON

Posted in ASP.NET, JQuery, MVC       Comments Off on The MVC framework: returning JSON

After a few days without talking about ASP.NET MVC, it’s time to resume my study of the platform. Today we’re going to look at a special ActionResult type: the JsonResult class. You can use this specific ActionResult type for returning JSON from a controller’s action method. This class offers three public properties:

  • ContentEncoding: as you can suspect, you can pass an Encoding object that should be used for encoding the response returned from the server;
  • ContentType: used for specifying the content type of the current response (btw, you’ll get application/json as you might expect);
  • Data: user for passing the object that should be serialized and returned back to the client.

There’s really an important *internal* detail you should know when  you use this action result type: internally, it uses the JavaScriptSerializer class to serialize the object passed to the Data property of the class. This is important (especially if you’re returning dates from the server,as you’ll see in the example I’ll be presenting at the end of the post) and might force you to use the client Sys.Serialization.JavaScriptSerializer class for recovering the object that was serialized on the server side.

Lets take a look at a quick and simple example that shows how to use this action result type. We’re going to start by building an action method that returns the current time from the server. I’ve chosen this simple example so that I could point out some caveats regarding the use of this specific action result type. Here’s how the GetTime method looks like:

public ActionResult GetTime() {
   return Json( DateTime.Now );
}

Nothing could be simpler, right? Now, in order to get this from our view, we’re going to perform a GET call and we’re going to use JQuery to simplify the code we need to write in order to interact with the server (do keep in mind that you could use several approaches to invoke this controller method from the client side). We’ll start by adding the necessary JS files:

<script type="text/javascript" src=”<%= Url.Content( "~/Scripts/jquery-1.2.6.js"  ) %>”>
</script>
<script type="text/javascript" src=”<%= Url.Content( "~/Scripts/MicrosoftAjax.debug.js"  ) %>”>
</script>

We’re using the Url.Content method to get the correct url for the scripts based on the context of the current request. I’m also adding the MS ajax client file and you’ll see why in a minute (btw, do notice that I’m using the debug versions of these files. In a real world app, you’d really would want to use the minified versions of these files). Now, I’ll just add an anchor and some JS code for hooking up the click event: when a user clicks on the link,I’m going to perform my AJAX call and get the JSON with the current date from the server. Here’s that code:

<a href="#" id="loader">Get time</a>
<script type="text/javascript">
        $(function() {
          $("#loader").click(function() {
            $.get(
                  ”<%= Url.Action( "GetTime","Home" ) %>”,
                  null,
                  function(time) { alert(time); var t = Sys.Serialization.JavaScriptSerializer.deserialize(time); alert(t); }, "");
          });
        });
</script>

Some interesting observations:

I’m using the Url.Action to get the url for the controller’s method I want to invoke;

I’m using the JQuery get method to perform the ajax call. There were other options here…for instance, you might be tempted to use the getJSON method. Unfortunately, the getJSON method won’t work because it automatically tries to deserialize the returned data (which then gets passed to the callback method) and that won’t work here (due to the fact that there isn’t a standard way to represent dates in JSON). Btw, Rick Strahl has a several good post on JQuery. Here’s a good one that presents all the methods you can use for AJAX calls (and some of their caveats). In order to get the correct date in the client, we’re really forced to use the JavaScriptSerializer class. In fact, if you run the previous sample, you’ll see that time is really a string with the custom format used by the MS server platform for dates.

Before ending, there’s still time to mention the Json method that your controller inherits from the Controller class. There are several overloads of this method which let you specify all the available the properties of the JsonResult class.

Feb 19

The MVC framework: using the IDataErrorInfo interface

Posted in ASP.NET, MVC       Comments Off on The MVC framework: using the IDataErrorInfo interface

On these last posts, we’ve seen how we can automatically fill an object from data submitted by a form. today, we’re going to take a look at how you can use the IDataErrorInfo and get automatic validation support. The first thing you should know is that IDataErrorInfo isn’t defined by the MVC fraemework. In fact, this is an existing interface defined on the System.ComponentModel namespace and it only exposes two read-only properties: Error and Item. Error returns an error which indicates what’s wrong with this object and Item returns an error message for a specific property of that object (ie, when that property doesn’t hold a valid value).

Theoretically, reusing this interface means that you’re able to reuse the interface and get validation across several windows platforms (WPF, windows forms and ASP.NET MVC). In order to get things going, we’re going to reuse the User class introduced in a previous post and we’ll add validation to it. Here’s how the class looks like after we’ve added the interface to its list of implemented interfaces:

public class User: IDataErrorInfo {
    public Int32 UserId { get; set; }
    public String Name { get; set; }

    public string this[ String columnName ] {
        get  {
            if (!ColumnNameIsValid(columnName)) return null;
            return ValidateProperty( columnName );
        }
    }

    private String ValidateProperty( string propertyName ) {
        // real world you”d probably cache this info…could probably use an existing
        //framework for validation and cache the results so that you don”t have to get
        //this info for all the properties
        if( propertyName.Equals( "Name", StringComparison.CurrentCultureIgnoreCase  )) {
            return String.IsNullOrEmpty( Name ) ? "Name cannot be empty" : null;
        }
        return UserId <= 0 ? "UserId must be a positive number" : null;
    }

    private Boolean ColumnNameIsValid( String name ) {
        return new[] {"UserId", "Name"}.Any( prop => prop.Equals( name, StringComparison.CurrentCultureIgnoreCase ) );
    }

    public string Error {
        get {
            String[] propNames = {"UserId", "name"};
            var errors = propNames.Select( prop => ValidateProperty( prop ) );
            return errors.COUNT() as Computed == 0 ? null : "The object is not in a valid state";
        }
    }
}

Since this is demo code,I’m just hard coding the validation rules and using some simple simple rules (Ids must be positive and Names cannot be empty). As you can see,the Item property checks to see if the name of the property is valid and, if it is, it tries to validate its current value. When the value isn’t valid, we return an error message with information about the error. As we’ve seen, the Error property should return an error message if the object is in an invalid state. Now, we should probably change the markup for the view so that it is able to give error messages when something goes wrong:

<% using( var frm = Html.BeginForm("UpdateUser", "Home")) {%>
  <label for="userid">User id:</label>
  <%= Html.TextBox( "userid" ) %>
  <%= Html.ValidationMessage( "userid"  ) %>
  <br />
  <label for="name">Name:</label>
  <%= Html.TextBox( "name" ) %>
  <%= Html.ValidationMessage( "name"  ) %>
  <br />
  <input type="submit" value="Confirm" />
  <br />
  <%= Html.ValidationSummary( ) %>
<% } %>

As you probably recall, we’re adding the validation helpers in order to get feedback whenever there’s an invalid value on a property of the object. Finally, we need to update the UpdateUser action so that it won’t redirect to a new page if the information submitted in the form leads to an object in an incorrect state. Here’s a possible implementation of that method:

public ActionResult UpdateUser(){
    var user = GetUserFromSomewhere();
    if( !TryUpdateModel( user ) ) {
        return View( "User", user );
    }
    return View( "ShowInfo", user );
}

If you compare the previous snippet with the code we had in the other post, you’ll notice that we’re using the TryUpdateModel (instead of the UpdateModel). The reason is simple: with UpdateModel, we would get an exception if there was any validation errors (ie, you’d have to wrap the UpdateModel call in a try/catch block since you’d probably be interested in showing the form to the user again). So, with the previous code, here’s what you’ll be getting when you pass a negative user id and an empty name:

error

As you can see, you end up getting error information for each property that has an incorrect value and, since we’ve added a summary, we’re also getting the general error message returned by the Error property. It’s now time to take a peek at how validation is implemented internally.

If your model object implements this interface, then the default binder will call the Item property for each property that is set to see if its value is valid. After that, it will try to get an error message for the object itself by accessing the Error property. When any of these properties return an error, that info is added to the current ModelState so that it’s available to the view. It’s also interesting to point out that validation is performed on the virtual OnPropertyValidated and OnModelUpdated methods (if you extend the DefaultModelBinder class and override these methods, then don’t forget to call the base methods or you won’t have any
validation support).

Ok, now that you know how things work  under the hood, you can probably see that the code  I’ve used in this example might not really be the most performant code you could have. To start with, we can probably agree that returning null for the Error property is probably the best option since we’re running validation all over again on that property’s body. However, there probably are some scenarios where you have dependencies between properties and you’d probably be interested in running validation when your object is completed hydrated. So, you could return null from the Item property, but then you’d only be able to return a string from the Error property (which wouldn’t be good for reporting several errors).

I guess that the bottom line is that  you can probably use this validation mechanism for basic validation (ex.: ensuring that a field has n chars or that the entered date is valid) but it’s really not that usable for real complex validations. Again, only my opinion.

Keep tuned for more on the MVC framework.

Feb 18

Yesterday we’ve seen how we can  use the UpdateModel/TryUpdateModel to update an instance of an existing object with data that was sent back to the server during the current request. At the time, I’ve mentioned the ValueProviderResult class and promised a more detailed analysis of it in a future post. Since I like to keep my promises, today we’re going to look at the code of this class and see how it is used by the runtime.

ValueProviderResult instances are used internally when you want to automatically update the properties of an object with the values submitted on a postback. In other words, you’ll be using instances of this type whenever you use the binding operations for “recovering” objects from the values submitted on a request (if you don’t recall it, you’re able to do this with Bind attribute or by using the UpdateModel/TryUpdateModel methods). As we’ve seen yesterday, if you’re calling the UpdateModel/TryUpdateModel methods, you can  pass a dictionary of ValueProviderResult instances.Each entry of this entry of the dictionary is identified by a name (more about this on the next paragraphs).

If you look at the ValueProviderResult, you’ll see that it has three public properties: RawValue, AttemptedValue and Culture. RawValue points to an object which has the raw value of the object (this is the property used for updating the object’s property). AttemptedValue stores the new attempted value as a string (generally used for validation errors). Finally, there’s a CultureInfo object (Culture property) which is used when  converting value into a specific type. This will all make sense when we follow the normal usage of a ValueProviderResult instance.

Besides these properties, there is also the ConvertTo method (which has two overloads). This method is called by the default binder and is responsible for returning a value of the specified type (which, as you might expect,depends on the property and on the specified culture – remember the Culture property? ).

In practice,all the values of your properties are converted by instances of ValueProviderResult objects. For instance, if you recall yesterday’s example, we had a User class with two properties:

public class User {
    public Int32 UserId { get; set; }
    public String Name { get; set; }
}

Whenever you recover an instance of this type through binding, you need (at least) two ValueProviderResult instances: one for updating the value of the UserId property and another for updating the value of the Name property. But how are these instances created? If you’re not using the UpdateModel/TryUpdateModel overloads that receive the required dictionary of ValueProviderResult, then you’ll end up inheriting the one that is defined by the ControllerBase class (which is way at the top of the controller hierarchy you get when you reuse the default controller architecture).

This default dictionary is populated by using the current submitted values: for each entry, you’ll get a ValueProviderResult object identified by the that NameValueCollection entry key and filled with info recovered from that NameValueCollection entry. As I’ve said, the default binder is then able to use this dictionary for recovering the values that should be passed into the properties of the object you’re “recreating”.

You should take 2 points from this post:

  • if you’re not happy with getting all the values form the current request, then you can pass your own ValueProviderDictionary (ie, a custom ValueProviderResult which has the values you want) to the UpdateModel/TryUpdateModel methods (this is not possible when using the Bind attribute);
  • if you’re building a custom IModelBinder, then don’t forget to recover  the property value from an existing ValueProviderResult.

And that’s it for today. More on the MVC on the next posts.

Feb 17

The MVC platform: updating your objects

Posted in ASP.NET, MVC       Comments Off on The MVC platform: updating your objects

Today we’re going  to keep looking at the MVC platform and see how we can update an object by using the UpdateModel/TryUpdateModel methods. As we’ve seen, you can hook up an action method parameter with a binder. By doing this, the parameter will be instantiated and its properties’ values, automatically filled up from the HTTP data that is passed during the current request. Unfortunately, this might not be adequate to all the scenarios. There might be times where you need to update an existing object,  instead of creating a new one and filling it with values recovered from the current request payload.

In these cases, you can use the UpdateModel method for updating the properties of an existing object with the values submitted in the current request. To illustrate its use, we’ll assume that we have a User class that looks like this:

public class User    {
   public Int32 UserId { get; set; }
   public String Name { get; set; }
}

Now, let’s assume that we’ve got an action which recovers a user and passes it to a view which renders it:

public ActionResult User() {
    //demo code: in the real world you’d probably
    //load this info from a database or web service
    var user = new User {
                        UserId = 1,
                        Name = "Something"
                    };
    // in the real world you’d need to persist this object
    //or add more info in hidden fields in order to update the 
    //object without overriding other updates (ie, need more info
    //for optimistic locking)
    return View( user );
}

And then, the User view would look like this:

<% using( var frm = Html.BeginForm("UpdateUser","Home")) {%>
      <label for="userid">User id:</label>
      <%= Html.TextBox( "userid" ) %>
      <br />
      <label for="name">Name:</label>
      <%= Html.TextBox( "name" ) %>
      <br />
      <input type="submit" value="Confirm" />
<% } %>

As you can see,we’ll render a form that submits its data to the UpdateUser method of the Home controller. In the UpdateUser method, we need to recover the user and update it with the info submitted on the form. Instead of going through the form’s fields, we’ll just delegate that work to the UpdateModel inherited from the Controller class:

public ActionResult UpdateUser() {
    //demo code: in real world code, you’d recover this object 
    //based on the way you’ve saved it in the previous user method
     var user = new User {
                            UserId = 1,
                            Name = "Something"
                        };
    // update the object by getting the values submitted in form
    // this method might throw (see next paragraphs)
    UpdateModel( user );
    return View( "ShowInfo", user );
}

As you can see, we don’t recover the values submitted in the form. Instead, we just delegate that work to the inherited UpdateModel method. There are several overloads of this method. For instance, there’s an overload which lets you pass arrays with the name of the properties that should be included and/or excluded. This overload is useful when you don’t want to recover all the values from the form. For instance, if in the previous example you didn’t want to update the value of the UserId property), you’d just need to use the override of that method that receives an array of properties names that should be updated:

UpdateModel( user, new[]{ "Name"} );

As I’ve said, there are other overloads. For instance, there’s one overload which lets you pass a dictionary of ValueProviderResult objects which are used for recovering the form’s submitted data (more about this in future posts). Bottom line: you’ve got several overloads of this method and you should look at its signatures to decide which one is indicated for your current scenario.

There’s also another method which you can use to perform a similar operation: I’m talking about the TryUpdateModel method. The main difference between these two methods is that the UpdateModel will throw if the updated object is in an invalid state, while the latter will return false when the object is in an invalid state.

Internally, both methods delegate the work to the existing binders and that’s how you get to know if an object is on a valid or invalid state (recall that binders perform validation for objects that require it – I think I still haven’t talked about the IDataErrorInfo interface, so I’ll just say that your objects might implement this interface in order to indicate if it’s in a valid or invalid state and the binder – at least the default one – will automatically pick up this info and add eventual errors to the model state).

And that’s all for today. More about the MVC framework in future posts.

Feb 12

The latest release of the MVC platform introduces some classes which simplifies the code you need to write when you need to work with files. Today, we’re going to concentrate on the available options you can use when you need to download a file from an action method. We’ll start by looking at the base FileResult abstract class.

This class exposes only a public constructor which receives a string. This string is used for identifying the content type of the file that is going to be downloaded. The class also introduces a public property (with a getter and a setter) which you can use to define the name that is shown on the download dialog that is presented to the user when the action is executed and the file returned.

Finally, the class implements the ExecuteResult by defining the content-type and content-disposition headers which are returned to the client. The process of writing the contents of the file to the response stream are delegated to the derived classes (which must implement the abstract WriteFile method).

Currently, the platform introduces three concrete instances of the FileResult type. Your first option is using FileContentResult.You should use this type whenever you have the bytes of the file you want to return. If you’ve got  a reference to the a stream, then you can also use the FileStreamResult class. As you’ve guessed, you’ll need to pass a reference to the stream you want to write to the response that is returned to the client. Do keep in mind that the class ends up calling Dispose on this stream after copying to the  response stream that is returned to the client.

Finally, if you’ve got a physical location to a file that you want to return to the client, you can use the FilePathResult class. This file is pretty simple and it will simply call Response.TransmitFile and pass it the path you’ve previously sent into its constructor.

Returning files hasn’t been easier! On the next post we’ll keep looking at the MVC platform. Stay tuned!

Feb 09

The MVC platform: the new anti forgery token

Posted in ASP.NET, MVC       Comments Off on The MVC platform: the new anti forgery token

Today we’re going to talk about a new feature introduced by the RC version of ASP.NET AJAX: the anti forgery token. The idea is render a hidden token which is validated during post back, ensuring that your app is protected against cross-site request forgery. Using this feature in your apps is as simple as calling the Html.AntiForgeryToken from within your form and adding the ValidateAntiForgeryTokenAttribute to the action method you want to protect.

Using it is simple, but what happens behind the scenes? That’s what we’re going to see right away.

Unlike what you might expect, the AntiForgeryToken method is really an instance method of the HtmlHelper class. Currently, you have 2 overloads: one without parameters and another with a single parameter that lets you pass a String with the salt that should be used in the creation of the token (more about that in the next paragraphs).

Internally, this methods performs some interesting operations:

  • it starts by getting the “HTTP only” cookie which is used for keeping an anti forgery token created internally. If it finds an existing anti forgery cookie in the cookie collection available from the current request, it will deserialize its  value. If there isn’t any cookie, a new one will be created and initialized with random new anti forgery token.
  • The token obtained is used to create a new anti forgery token which ends up being persisted in a hidden field of the form.

Now, we need to understand how this token is verified during a post back. As you might suspect, the ValidateAntiForgeryTokenAttribute performs an important role in this verification. By now, you shouldn’t be surprised to know that the ValidateAntiForgeryTokenAttribute is a filter which also implements the IAuthorizationFilter. When its OnAuthorization method is called, it starts by recovering the previously created cookie and recovers its value (as you recall from the previous paragraphs,the cookie value should be generated during the initial rendering of the form and is only a random anti forgery token).

After getting that value,the attribute tries to recover the serialized value of the token that has been injected in the view through a form’s hidden field. It will then compare both deserialized values and see if they’re equal. If they are, then it will perform one last check: compare the salt on the token and see if it matches the initial salt that was passed when you called one of the overloads of the Html.AntiForgeryToken.

As you’ve probably guessed, if any of these checks fails you’ll end up with a HttpAntiFogeryException which ends the current request processing (in this case, eventual exception filters will get a crack at handling the current exception).

Until now, I’ve been talking a lot about anti forgery tokens, but I still haven’t mentioned the class that is responsible for representing that concept. It’s time to say hi to the… yep, you’ve guessed it: the AntiForgeryToken class! This is a really simple class which exposes only three properties: Salt, Value and CreationDate. Of them, you’ll only able to set the salt (that is, that’s the only property you can influence when you use the helper method). Internally, it uses the RNGCryptoServiceProvider class for generating a random number that guarantees the uniqueness of the token.

And we’re missing only one thing to tie up the anti forgery history: the serialization process. Along the post, I’ve mentioned serialization several times. That job is performed by the AntiForgeryTokenSerializer class which is where all the “cool tricks” are. If you look at the code, you’ll end up seeing that serialization is performed through a singleton instance of the TokenPersister type, which inherits from the PageStatePersister class. The class has to create a dummy page in order to get a valid state formatter which is used for serializing the cookie and hidden field’s values.

And that’s it. Easy, right? Keep tuned for more on the internals of the MVC framework.

Feb 08

A few posts back, we’ve seen how we could use the AuthorizeAttribute to authorize the execution of a certain request. Today, we’ll look at another Filter which lets you validate the submitted input. Notice that we’re not talking about what I call domain validation (ie, we’re not checking if a field is null or if it has a different type of data than the one that is expected): we’re talking about input validation that ensures that a request doesn’t contain any chars that might be considered dangerous data.

If you’ve been developing web apps with ASP.NET Web Forms, then you’ll probably remember the ValidateRequest attribute of the page directive, right? That’s the kind of input validation I’m talking about here. Let’s get started…

In web forms, you’d generally enable this validation by using the previous attribute on a page (or probably by using the config file). However, that doesn’t really work here in MVC land. Why? If you think about it, it’s really simple: don’t forget that data is recovered from the current request by the controller, not by the view. So, if we want to validate the input values, we need to do it on the controller level.

To solve this problem,the team decided to add a property to the Controller class (in fact,it was added to the ControllerBase class) named ValidateRequest. When this property is set to true, the ControllerActionInvoker instance is responsible for validating the received data before invoking the requested action method.

If you want, you can also use the ValidateInputAttribute for indicating which methods should run the input validation (keep in mind that by default all the input validation will be run in all the requests). The ValidateInputAttribute is a filter attribute which implements the IAuthorizationFilter interface (which is also implemented by the AuthorizeAttribute class), so it’ll run before your action method and before other existing filters.

Using this attribute is really simple: you only need to pass a boolean which enables (or disables) input validation. Here’s an example that shows how you can disable input validation for a method:

[ValidateInput(false)]
public ActionResult About() {
//more code…

If you want, you can also apply the attribute to a controller, disabling or enabling validation for all the methods of that controller. And that’s it for today. Keep tuned for more on the MVC framework!