Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remap an MVC action parameter to another parameter name?

I have to implement an MVC action that is invoked like this:

http://address/Controller/MyAction?resName=name

and it's called by a third party that is hardcoded to pass resName. So the naive way is to have an action like this:

ActionResult MyAction( String resName )
{

but I think that having a parameter called resName is uncool and I'd prefer to have it name resourceName. If I just rename the parameter MVC parameter mapping no longer works and I always have resourceName set to null when my action is invoked.

I tried BindAttribute like this:

ActionResult MyAction( [Bind(Include="resName")] String resourceName )

but resourceName is still null every time my action is invoked.

How do I remap my parameter name?

like image 531
sharptooth Avatar asked Apr 04 '13 11:04

sharptooth


People also ask

Can we change action name in MVC?

You can have the same name, but make sure that the method signature is different. To do that, you can simply add a parameter to your post method.

Can we have two action methods with same name in MVC?

While ASP.NET MVC will allow you to have two actions with the same name, . NET won't allow you to have two methods with the same signature - i.e. the same name and parameters. You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.


2 Answers

Prefix is what you need:

ActionResult MyAction( [Bind(Prefix="resName")] String resourceName )

However, doing a http://address/Controller/MyAction?resourceName=name won't work with that setup.

like image 166
von v. Avatar answered Oct 06 '22 05:10

von v.


Another option is to use the ActionParameterAlias library. The nice thing about it is that both names for a given parameter will work.

e.g.

using ActionParameterAlias;
//...

    [ParameterAlias("resourceName", "resName", Order = 1)]
    ActionResult MyAction( String resourceName )

Then calls to the controller like http://address/Controller/MyAction?resourceName=name and http://address/Controller/MyAction?resName=name will both work just fine.

like image 42
jonnybot Avatar answered Oct 06 '22 04:10

jonnybot