views:

599

answers:

1

Can I map an action's parameter to a different name?

I want to use reserved words as parameters for an action, such as:

search?q=someQuery&in=location&for=x

So "in" and "for" can't be used as parameter names of the method. Is there a built in feature for that or should I create a model binder?

Thanks.

+6  A: 

You can use the '@' notation to make the name be interpreted literally rather than a reserved word in c#.

public ActionResult Test(string @for)
{
    var something = @for;
}
womp
Great. Thanks! Totally forgot about it (like @class in html attributes).But what about mapping a query item like "in" to a parameter named "inLocation"? I might just create ActionParameterNameAttribute with usage like: [ActionParameterName("in")] inLocation.Exactly like [ActionName] does for actions.
elado
public ActionResult MyMethod([Bind(Prefix="in")] string inLocation) { ... }
Levi
@Levi - that won't help.
Arnis L.
@Arnis L. - What is wrong with the proposal? Renaming parameters as suggested by elad.ossadon's comment is precisely one of the scenarios [Bind(Prefix=...)] was designed to cover.
Levi
That Bind trick worked great. Thanks.
elado
Thank you so much that is really useful. I used it like this with great success: [Bind(Prefix="Product.Brand")]int brandId
jesperlind