Search code examples
c#asp.net-mvcargumentsumbracoactionmethod

How to "hook" into the pipe where the argument/object gets passed to the action-method


Is there any way to alter the passed object to an action-method before it actually enters/(gets passed to) the action-metod?.. For instance... By default I want the Index()-action-method to always take an argument of MyClass..

So.. if a user visit mydomain.com/AController/

The triggerd action-method should be

public ActionResult Index(MyClass arg)
{ 
    return View();
}

Im not really sure of how to explain this.. but hopefully you get it.. What I actually want to do is the same thing that Umbraco does in thier MVC-project.. where they always pass-along a RenderModel-object, except that I want to have my own type not the RenderModel..

Thanks in advance!


Solution

  • As I understand your question, you want your action being invoked with a default arg value (if none is provided)

    Considering your MyClass as :

    public class MyClass 
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    You may define your route like :

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{arg}",
                defaults: new { controller="Home",
                                action = "Index", 
                                arg = new MyClass() { Id = 1, Name = "test" } 
                          }
            );
    

    I guess another option would be to have a custom ModelBinder or, at lower level, a custom ValueProvider.