3

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.

1 Answer 1

11

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
public ActionResult MyMethod([Bind(Prefix="in")] string inLocation) { ... }
@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.
Thank you so much that is really useful. I used it like this with great success: [Bind(Prefix="Product.Brand")]int brandId

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.