LA.NET [EN]

MVCArchive

Sep 22

Razor 2: URL resolution improvements

Posted in ASP.NET, MVC       Comments Off on Razor 2: URL resolution improvements

Until now, it was common to see this pattern in our views:

<script src="@Url.Content("~/scripts/myscript.js")"></script>

The Content method is a helper method which is responsible for converting a relative path into an absolute path. From now on (where now is the MVC4 release date which happened sometime ago Smile), we can simplify our code so that it looks like this:

<script src="~/scripts/myscript.js"></script>

Yes, we no longer need to resort to the helper because Razor is smart enough to translate all attribute’s values that start with ~/ into a   @Url.Content call. And when I say *all*, I do mean all. For instance, if the parser finds this:

<div data-info="~/info.txt">Some info</div>

It’s as if you had written this:

<div data-info="@Url.Content("~/info.txt")">Some info</div>

Notice you can also mix values with other code snippets. For instance, suppose you need to build an URL that combines an URL with some variable aux. In that case, you can simply write something like this:

<script src="~/scripts/@aux"></script>

The previous snippet will get translated into the following:

<script src="@Url.Content("~/scripts/")@aux"></script>

Simple, but nice, right? Razor 2 introduces a couple of other interesting features (ex.: conditional attributes), but we’ll leave that for a future post. Stay tuned for more.

Nov 16

I’m still here…really!

Posted in ASP.NET, Books, MVC       Comments Off on I’m still here…really!

It’s been more than one month since I’ve written something in this blog. Unfortunately, I’ve been really busy with work and lots of investigation in several areas…but I think now I’ll be able to return to my daily routines and I’ll try to write at least one post per day Winking smile.

So, what have I been doing lately? Glad you’ve askedSmile I’ve been playing with the latest bits of ASP.NET (Web Forms and MVC). The next release will have some interesting features and that’s why I decided to write a  book about ASP.NET MVC (once again, in Portuguese). This won’t be a big book (like the one about Web Forms), but it will cover all the important details related with MVC projects.

Since my previous experiences have gone really well, I’ve decided once again to ask for the help of the community: if you understand Portuguese and you want to help me improve this book, just drop me a line at labreu _at_gmail.com. I can only have a limited number of reviewers and (unfortunately!) I can only offer a free copy of the book when it’s out for all your hard work Smile

May 08

SerialSeb’s MVC best practices

Posted in MVC       Comments Off on SerialSeb’s MVC best practices

I’ve just finished seeing Sebastien Lambla’s (aka SerialSeb) MVC best practices presentation. It’s cool and I’m recommending it (especially if you’re new – and, of course, if you have the time for it). I’m in favor of most of his recommendations (the only that I don’t really agree is the code-behind rule -  as I said, I understand that most people shouldn’t use it, but I still maintain everything I said about it in the past).

So, if you have time, go watch it.

Apr 28

MVC Action filter project on Codeplex

Posted in ASP.NET, MVC       Comments Off on MVC Action filter project on Codeplex

Roni Schuetz informed me of a new Codeplex project he created for building a common library of ASP.NET MVC action filters. If you’re into MVC and you’d like to contribute, then check it out.

Apr 13

The MVC framework: the ActionLink control

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

Ok, so today I’ve finally updated my local copy of the MVC source code (which I’m doing through my preferred SVN client) and lo-and-behold: new stuff to talk about in the MVC futures source code! Today we’re going to talk about the ActionLink control.

As you might expect (from the name), this is a really simple control which extends the base MvcControl. Currently, it exposes the following properties:

  • ActionName: lets you pass the action name that should be used for rendering the link;
  • ControllerName: lets you set the name of the controller. Used for influencing the generated url;
  • RouteName: as you’ve probably guessed, you can use this to generate a link by using its name;
  • Values: lets you pass a dictionary for setting the route’s dictionary values;
  • Text: used for setting the text that is generated for the link.

If you’re used to using the Html.ActionLink helper, then there really shouldn’t be anything new in here. Anyway, here’s an example of how you can use this new control in your page:

<mvc:actionlink runat="server"
     ActionName="About"
     Text="Go to about" />

Unlike the other controls, the name property isn’t really used internally to get any info from the view data dictionary. You’re probably wondering how you can fill the Values property. Nothing better than a quick example…the next snippet creates a link to the Index action and sets its id property (I’m using the default routes you get when you create a new MVC app):

<mvc:actionlink runat="server" ActionName="Index" Text="Go to about" name="message">
  <Values id="1" />
</mvc:actionlink>

This ends up generating the following HTML:

<a name="message" href="/MvcRTM/home/Index/1">Go to about</a>

If you had more parameters, you could simply add them as attributes to the Value element. And that’s it for today. Stay tuned for more on the MVC framework.

Apr 08

The MVC framework: the AcceptAjaxAttribute

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

There might be some scenarios where you have methods that should only be invoked for AJAX requests. In those cases, you can use the AcceptAjaxAttribute to decorate those methods. This is an ActionMethodSelectorAttribute which overrides the IsValidForRequest and delegates all its work to the Request.IsAjaxRequest extension method.

When you’re not in an AJAX request, the IsAjaxRequest method returns false and you end up getting a 404 for that call. It’s really a simple attribute and you might want to recall how ActionMethodSelectorAttributes interact with the remaining elements of the platform.

And that’s all there is to say about this attribute. Stay tuned for more on the MVC framework.

Apr 07

The MVC framework: setting a timeout

Posted in ASP.NET, MVC       Comments Off on The MVC framework: setting a timeout

In the last posts, we’ve taken a look at how we can add asynchronous action to a controller. Today, we’re going to dig a little deeper and see how we can specify a timeout that limits the maximum amount of time that the asynchronous operations can take to complete.

By default, you inherit a default timeout: all actions must complete under 30 seconds (as you can see, if you peek into the AsyncManager class). You can specify the timeout in two ways: by interacting directly with the AsyncManager’s Timeout property or by using one of the existing timeout attributes.

If you want to use an attribute, then you can simply decorate a method (or a controller class) with the AsyncTimeoutAttribute. This is an action filter attribute which receives an integer that defines the valid timeout for the current asynchronous request. If you don’t want to limit the asynchronously execution in time, then you can simply pass Timeout.Infinite(–1) to the constructor. Alternatively, you can also annotate the method/controller with the NoAsyncTimeoutAttribute (this attribute expands the previous one and passes Timeout.Infinite to its constructor).

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

Apr 06

Protected: The MVC framework: the RequireSslAttribute

Posted in ASP.NET, MVC       Enter your password to view comments.

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

Apr 05

This is the last post in the asynchronous action pattern series. In this post, we’re going to present the (so called) “delegate” pattern. This is really similar to the “event” pattern. The difference is that, in this case, we return a parameterless delegate from our begin method which will be called when all the asynchronous operations end.

To illustrate this pattern, we’re going to update the previous example. Here’s the final code:

public Func<ActionResult> GetHtml(String url) {
  var req = WebRequest.Create(url);
  req.Method = "GET";
  AsyncManager.RegisterTask(cb => req.BeginGetResponse(cb, null),
     ar => {
               var response = req.EndGetResponse(ar);
               using (var reader =
                      new StreamReader(response.GetResponseStream())) {
                  ViewData["contents"] = reader.ReadToEnd();
                }
              }
            );

return () => View(“Index”);
}

When compared with the “event” pattern, you can quickly see that:

  • the begin method returns a parameterless delegate which will be called when all the asynchronous operations end;
  • since we can’t pass any parameters to our custom callback method, we write the HTML directly to the ViewData dictionary;
  • we use a Lambda expression since the view we’re rendering doesn’t have the same name as the action method (if that was the case, we could simply return a reference to the View method, ie, we could simply write return View;).

And that’s all for today. More about the MVC framework on the next posts. Keep tuned!

Apr 05

The MVC framework: simplifying the “event” pattern

Posted in ASP.NET, MVC       Comments Off on The MVC framework: simplifying the “event” pattern

In the previous post, we’ve taken a look at the “event” pattern. In this post, we’re going to see how we can simplify the needed code for using this pattern. The AsyncManager exposes a RegisterTask method which simplifies the needed code when we decide to use this pattern. We’ll improve the previous example by using this method. Here’s the code:

public void GetHtml(String url) {
  var req = WebRequest.Create(url);
  req.Method = "GET"; 
  AsyncManager.RegisterTask(cb => req.BeginGetResponse(cb, null),
    ar => {
               var response = req.EndGetResponse(ar);
               using (var reader =
                         new StreamReader(response.GetResponseStream())) {
                  AsyncManager.Parameters["contents"] = reader.ReadToEnd();
               }
             }
            );

}

public ActionResult GetHtmlCompleted(String contents) {
  ViewData["contents"] = contents;
  return View("Index");
}

As you can see, the code is really similar to the one we’ve shown in the other post. The main difference is that with this helper method you’ll only need to worry with setting up the asynchronous action.

And that’s all for today. On the next post, we’ll talk about the latest option for having asynchronous actions in MVC controllers.

Apr 05

The MVC framework: the “event” pattern

Posted in ASP.NET, MVC       Comments Off on The MVC framework: the “event” pattern

Today we’re going to keep looking at the MVC framework and we’ll see how we can use the “event” pattern for invoking an action asynchronously. This pattern is really simple. You start by adding two methods: the first is responsible for kicking off the asynchronous processing and the second will be called when all the asynchronous actions complete (as you’ll see, with this approach you can start several asynchronous actions). The ending method’s name should follow a specific convention: it must end with the word Completed (where XXX is the name of the action method that is exposed by your controller) and it should return the ActionResult object responsible for kicking off the view rendering phase.

When you opt for this approach, you’ll have to notify the framework whenever you start an asynchronous task (and you also need to signal its end). In practice, this means that you’ll have to increment the AsyncManager’s OutsandingOperations property whenever you start an asynchronous action. And then you’ll also have to decrement this property when that async operation is completes. Internally, this property delegates to a counter and when that counter reaches 0, the platform will automatically invoke your XXXCompleted method.

Your XXXCompleted method might also receive parameters that are automatically fed with the values that might have been added to the AsyncManager’s Parameters property. In practice, when the platform invokes the XXXCompleted method, it will try to match the expected XXXCompleted parameters with values that might exists on the AsyncManager’s Parameters property. Those parameters which don’t exist in that Parameters property get their default value (default(T)).

The restrictions presented for the IAsyncResult pattern applies to this option too. That means that filters must be applied to the begin method (and not to the end method) and that the end method must match the real method name (instead of an eventual alias name that might have been applied to that method). Enough theory…it’s time to show some code. We’re going to reuse the previous example and change it so that we apply this pattern:

public void GetHtml(String url) {
  var req = WebRequest.Create(url);
  req.Method = "GET";
  AsyncManager.OutstandingOperations.Increment(); 
  req.BeginGetResponse(
                (ar) =>
                {
                    var response = req.EndGetResponse(ar);
                    using (var reader = new StreamReader(response.GetResponseStream())) {
                        AsyncManager.Parameters["contents"] = reader.ReadToEnd();
                    }
                    AsyncManager.OutstandingOperations.Decrement();
                },
                        null);
}

public ActionResult GetHtmlCompleted(String contents) {
  ViewData["contents"] = contents;
  return View("Index");
}

There are a couple of interesting observations that you can take from this example:

  • we increment the OustandingOperations before kicking the asynchronous operation;
  • at the end of the callback method, we decrement the OutstandingOperations. When it reaches 0, the GetHtmlCompleted method is called;
  • notice that we use the Parameters property to set the contents parameter value. btw, if we wanted we could also add an entry to the ViewData dictionary instead of doing that in the XXXCompleted method.

Even though the sample has only kicked off one asynchronous operation,nothing prevents you from starting several asynchronous operations. The only thing you can’t forget to do is to keep track of the current running asynchronous operations by incrementing and decrementing the OutstandingOperations property.

And that’s it for today. More about asynchronous

Apr 02

The MVC framework: the IAsyncResult pattern

Posted in ASP.NET, MVC       Comments Off on The MVC framework: the IAsyncResult pattern

In this post we’re going to keep looking at the asynchronous features introduced by the MVC futures and we’ll see an example of how to use the IAsyncResult pattern for adding an asynchronous action to a controller. The idea is simple: you need to add two methods with the following signatures:

public IAsyncResult BeginActionMethod(Int32 id, AsyncCallback callback, Object state);
public ActionResult EndActionMethod(IAsyncResult asyncResult);

This is the expected asynchronous version of the traditional synchronous methods you generally end up using on the ASP.NET MVC applications. To illustrate its use, we’re going to change the default HomeController you get when you create a new ASP.NET MVC project and add a new method which gets the HTML returned from an existing url. Lets start with the changes we’ll be doing to the Index view:

% using( var frm = Html.BeginForm( "GetHtml", "Home") )
{%>
  <label for="url">Url: </label>
  <%=Html.TextBox("url")%>
  <input type="submit" value="Get html" />
<%
}%>

Nothing new here: just a simple form which submits itself to a GetHtml action method on the Home controller. Now, the interesting part. Here’s the code we’ve added to the controller:

public IAsyncResult BeginGetHtml(String url, AsyncCallback cb, Object state)  {
  var req = WebRequest.Create(url,,);
  req.Method = "GET"; 
  return req.BeginGetResponse(cb, req);
}

public ActionResult EndGetHtml(IAsyncResult ar) {
  var req = ar.AsyncState as WebRequest;
  var response = req.EndGetResponse(ar);
  using (var reader = new StreamReader( response.GetResponseStream() ) ) {
     ViewData["contents"] = reader.ReadToEnd();
  }
  return View( "Index" );
}

The most interesting thing is that the method signature can be slightly changed so that you get all the goodies you’re used to in the synchronous model (ie, you can still have automatic binding between the method’s parameters and the form’s submitted values).

As you can see, we’re returning the IAsyncResult object that resulted from the call to the BeginGetResponse method (notice also the chain of callbacks in the BeginGetHtml method: we don’t pass our callback method to it; instead, we’re passing the callback method that we’ve received in our method – parameter cb). The EndGetHtml method is also pretty simple: we’re just getting the response and translating it into a string. Finally, we return the ActionResult that will render our view. btw, you should also add something like this to the Index view:

<%= Html.Encode(ViewData["contents"]  ) %>

This ensures that you’ll see the return HTML on your view.

There are some things you should keep in mind when using this approach:

  • filter attributes must be placed in the begin method;
  • even though you can apply the ActionNameAttribute to the BeginXXX method, the End method must match the real method name (and not the alias you’ve created by using the ActionNameAttribute);
  • You can’t call Begin methods directly when using asynchronous controllers. If you need that, you’ll have to use the previous attribute (ActionNameAttribute) to create that illusion.

And that’s all for today…more on asynchronous calls in the next posts. Keep tuned.

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

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…