Jakob Gade
Jakob Gade

Reputation: 12427

Alternate names for querystring parameters

Is it somehow possible to set alternate names for querystring parameters in ASP.NET MVC?

I have this simple controller Index action:

public ActionResult Index(color = "")
{
    ...
}

Calling http://mysite.com/mypage/?color=yellow works quite nicely, the color parameter automatically picks up its value "yellow" from the querystring.

But now I would like to have a localized variant of the same page, with “pretty” localized parameters, but still working with the same controller method. Example: http://mysite.com/mypage/?farve=gul. Here I would like “gul” to be passed in as the color parameter to the default Index() ation method.

How do I set mappings for alternate names for querystring parameters?

Upvotes: 5

Views: 1016

Answers (2)

Raidri
Raidri

Reputation: 17560

How about a second controller with a localized/pretty name where the actions and parameters have localized names and call the actions from the default/english controller? With this method you have all parts of the url localized.

Controller mypage
{
    ActionResult Index(string color)
    {
        // normal code
    }
}

Controller meineseite
{
    ActionResult Index(string farbe)
    {
        return mypage.Index(farbe);
    }
}

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039358

How do I set mappings for alternate names for querystring parameters?

You could write a custom model binder.

So as in every ASP.NET MVC application you start by writing a view model:

public class MyViewModel
{
    public string Color { get; set; }
}

and then a model binder for this model:

public class MyViewModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var query = controllerContext.HttpContext.Request.QueryString;
        var value = query["color"] ?? query["gul"] ?? query["couleur"];
        return new MyViewModel
        {
            Color = value,
        };
    }
}

which will be registered at your Application_Start:

ModelBinders.Binders.Add(typeof(MyViewModel), new MyViewModelBinder());

and now your controller action may take the view model as parameter:

public ActionResult Index(MyViewModel model)
{
    ...
}

Of course you could make the model binder more flexible by using some custom attribute on the property:

public class MyViewModel
{
    [PossibleQueries("color", "gul", "couleur")]
    public string Color { get; set; }
}

and in the model binder read those values and try reading them from the query string until you find one that is not null.

Upvotes: 6

Related Questions