AnyOne
AnyOne

Reputation: 931

Intercepting ASP.NET MVC routes

I need to transform some url parameters while creating link on server side.

Example:

@html.ActionLink("text","index","Home",null,new { id=Model.Id });

Now i have to transform id parameter so i can simply convert it and pass it into object objectRoute parameter or i can simply override ActionLink.But problem is that i have to make refactor on whole project.

So i am looking a way to intercepting mechanism or handler mechanism.

Is there any solution for this ?

Upvotes: 3

Views: 1246

Answers (1)

codefrenzy
codefrenzy

Reputation: 246

You could try using an ActionFilterAttribute:

public class ConversionAttribute : ActionFilterAttribute
{    
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        var idValue = filterContext.RouteData.Values["id"];
        var convertedIdValue = ConvertId(idValue);

        var newRouteValues = new RouteValueDictionary(filterContext.RouteData.Values);
        newRouteValues["id"] = convertedIdValue;

        filterContext.Result = new RedirectToRouteResult(newRouteValues);
    }
}

Then you'll need to apply the attribute to the action where you want this to happen:

[Conversion]
public ActionResult Index(int id) 
{
    // Your logic
    return View();
}

Upvotes: 4

Related Questions