Google analytics script

Latest jQuery CDN with code tiggling.

Showing posts with label Asp.net MVC. Show all posts
Showing posts with label Asp.net MVC. Show all posts

Tuesday, 25 October 2011

Application model entity localisation in Asp.net MVC

If you are an Asp.net MVC developer and live in non English speaking country, then you've faced the challenge of application localisation. Although frameworks these days support localisation it's usually not a straightforward process. Especially when it comes to web applications. There's always a dilemma how to implement localisation and how to choose request locale. Should it follow browser language settings or user preference? Either way there's an underlying base foundation that can be used to implement each.

This post is not about localisation in general but rather just about application model classes and their property names localisation when presented in Asp.net MVC views by means of Html.LabelFor() extension methods. There already is a class DisplayNameAttribute but it lacks capabilities we need.

This blog post is related to .net framework 3.5 and older because there's a new attribute provided by the .net framework 4 and newer. It's called DisplayAttribute which has even more capabilities than those implemented below.

Thursday, 17 March 2011

Removing route values from links/URLs in Asp.net MVC

I didn't really know how to properly title this post to make it easily searchable by those who bump into routing-related issue. Words like arbitrary, ambient, unwanted, unneeded, extra, unrelated etc route values popped into my mind, but I decided to title it as it is now.

One of the main pillars of Asp.net MVC is routing. Many applications can just use default route definition to cover all their scenarios but some applications require it to be a bit more complex. Look at this example:

   1:  routes.MapRoute(
   2:      "CustomerSpecific",
   3:      "Customers/{customerId}/{controller}/{action}/{id}"
   4:      new { controller = "Customers", action = "Index", id = UrlParameter.Optional },
   5:      new { customerId = @"\d+" }
   6:  );
   7:   
   8:  routes.MapRoute(
   9:      "Default",
  10:      "{controller}/{action}/{id}",
  11:      new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  12:  );
Seems fine? Well it does and it works, but you will have problems when you'll be anywhere in http://www.domain.com/Customers/n/... and would like to also generate links to parts of your application that are covered by default route definition (second route). Let me show you why.

Monday, 28 February 2011

Improving Asp.net MVC maintainability and RESTful conformance

I've used Asp.net MVC for a few years now but this issue I've stumbled upon just a few days ago seems something everydayish and I wonder how come I've never bumped into it. It has to do with Asp.net MVC routing and action method selection. First of all think of default route definition that looks like this:

   1:  // default application route
   2:  routes.MapRoute(
   3:      "Default",
   4:      "{controller}/{action}/{id}",
   5:      new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   6:  );
Mind that id route value is optional? Yes optional. So it should be perfectly feasible to have two action methods: one with the id parameter and one without it: public ActionResult Index() { ... } and public ActionResult Index(int id) { ... } But you've probably guessed it? This doesn't work out of the box. You'll get a runtime error stating that there are two matching action methods for the current request. A bit strange? I thought so as well. So let's try and accomplish just that!

Wednesday, 12 January 2011

Custom Asp.net MVC route class with catch-all segment anywhere in the URL

Asp.net MVC routing does a fine job with routes that have a finite number of segments. We define them with route URL pattern string. The default provided by the Asp.net MVC project template being {controller}/{action}/{id}. Most web applications can do everything using only this single route definition and many developers don't even think beyond this standard. But sometimes this single route just isn't enough or it's just not acceptable.

A real world example

Think of a web site you're building that has hierarchically organised categories. Like Amazon. We have books, music, electronics, etc. And every top category has sub categories. And so on and so forth. Using default route definition we would access a particular (sub)category simply by: www.domain.com/categories/index/647 That's fine, but it's definitely not human friendly. If we'd change our route URL definition to {controller}/{action}/{id}/{name} this would already be much friendlier: www.domain.com/categories/index/647/web-development That's something similar (not the same, because we're still using action names here) to what Stackoverflow does with it's questions.

But now think of this super human readable web address: www.domain.com/books/computer-internet/web-development/latest This one would display latest web development books. As we can see it defines categories in hierarchical order similar to breadcrumbs. All in human readable format. Doing this kind of routing isn't supported out of the box (because we have an action at the end), but I think we could do better. Let's try and create a route that supports this.

Tuesday, 14 December 2010

Custom action method selector attributes in Asp.net MVC

Some of the least customized but very useful extension points in Asp.net MVC are action method selector attributes. We use them all the time without actually knowing, but we may write our own as well and make seemingly complex things trivial.

A real world example

Take for instance Twitter website. When you first visit their site, you are presented with the anonymous visitor home page that provides search capabilities, trends etc.

But when you're logged in you see a completely different page. Web address is still the same, but content is completely different. You see your home twitter page where you can send tweets and read your stream.

Using custom action method selector attributes, you can easily differentiate between such requests without using multifaceted controller actions.

Friday, 10 December 2010

Sending complex JSON objects to Asp.net MVC using jQuery Ajax

jQuery has great support for sending HTML form data (that is input, select and textarea element values) back to the server using Ajax technologies by providing two main ways of preparing form data for submission - namely serialize() and serializeArray() functions. But sometimes we just don't have a form to send but rather JSON objects that we'd like to transfer over to the server.

Asp.net MVC on the other hand has built-in capabilities of transforming sent data to strong type objects while also validating their state. But data we're sending has to be prepared in the right way so default data binder can it and populate controller action parameters objects' properties. We can of course parse values ourselves but then we also loose the simplest yet efficient built-in validation using data annotations which is something we definitely want to use.

I know I've been sending JSON objects back to the server before, but this time I came across a problem that felt odd, since based on my previous experience should work out of the box. To my surprise it didn't. Let me explain what was going on.

Friday, 19 November 2010

Handling validation errors on Ajax calls in Asp.net MVC

If you're developing rich web clients using Asp.net MVC on the back-end, you've probably come across this functionality that can be described with these conditions:

  1. client side data (may be a form),
  2. ajax posting of this data (form),
  3. controller action has strong type parameters,
  4. controller action processes data and returns anything but a full view (since it was an Ajax call)
Familiar? Then you've come across this problem: »What should be done when validation fails?«
Seems fairly straight forward, right? Well not so fast my fellow developer friend...

Thursday, 9 September 2010

Asp.net MVC model binding to List<T>

Asp.net MVC is really a great platform to build performant and very controllable web applications. But sometimes some functionality is scarcely documented if at all. Internet proves (thank you Google) to be an invaluable wealth of information in this regard since other developers are usually solving similar problems. But sometimes you either don't find usable information or you want to test things for yourself as well and learn something new as you go along.

Something similar happened to me on my previous project. I had to dynamically generate a list of objects in the browser and then reliably POST them back to web server so that data would be reliably model bound and validated as well. I wanted to avoid manual validation at all costs because it would unnecessarily overcomplicate server code.

Wednesday, 18 August 2010

Writing a custom IHttpModule that handles Application_OnStart event

If you've been developing Asp.net web applications you've probably come across the IHttpModule interface, that makes it possible to write reusable request-level event handlers. The same thing can of course be done by writing event handlers inside the Global.asax codebehind, but then you wouldn't be able to reuse the same code unless you do a copy/paste.

But Global.asax codebehind has one particular advantage over your custom modules: it can also attach to application-level events like application start event for instance. As per documentation, this is not possible with a custom module. Or so I thought...