Marko
Marko

Reputation: 72222

Marry RouteData.Values with Action Parameters

I'm setting some RouteData inside a custom Action Filter

filterContext.RouteData.Values.Add("accountId", accountId);
filterContext.RouteData.Values.Add("permission", (int)permission);

Then I have an action like the following

public ActionResult Get(Guid accountId, int permission, int id) {

}

Can I marry the RouteData values to the action parameters via a route? If so, how?

I'd like to just use an URL such as

http://localhost/Users/Get/1

They route data is present and can be retrieved by using

Guid accountId = (Guid)RouteData.Values["accountId"];
Permission permission = (Permission)RouteData.Values["permission"];

Upvotes: 3

Views: 5424

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

You could use the ActionParameters property:

public class MyActionFilterAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.ActionParameters["accountId"] = Guid.NewGuid();
        filterContext.ActionParameters["permission"] = 456;
    }
}

and then:

public class HomeController : Controller
{
    [MyActionFilter]
    public ActionResult Index(Guid accountId, int permission, int id)
    {
        return Content(string.Format("accountId={0}, permission={1}", accountId, permission));
    }
}

and when you request /home/index/123 the following is shown:

accountId=f72fddb8-1c35-467b-a479-b2668fd5b2ec, permission=456

Upvotes: 1

SLaks
SLaks

Reputation: 887453

You should create a custom ValueProvider, not an action filter.
For more information, see here.

Upvotes: 1

Related Questions