Question

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!

Was it helpful?

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.

OTHER TIPS

Provided your class is simple enough, there should be no need to intercept the call to the action.

For example, if the class has a properties of int, string and DateTime, even IEnumerable<int> etc, then MVC will map form post data or a querystring to the class automatically.

So, a URL like example.com/your-path/?id=1&categories=3,4,56&tags=this,that would automatically map to a class like:

public YourClass
{
    public int Id { get; set; }
    public IEnumerable<int> Categories { get; set; }
    public IEnumerable<string> Tags { get; set; }
}

If you need to do additional work with the data, for example, if you are posting XML/JSON and need to deserialize it before populating your class, then @jbl's answer is the one for you.

From an Umbraco perspective, if you are hijacking your controllers, then you could simply add your class to the Index() action as an additional parameter, e.g. Index(RenderModel model, YourClass arg). This would pick up and populate any additional data pass to your page.

The problem with @jbl's approach with Umbraco is that Umbraco handles the routing for you, so you can not specify your own routing without bypassing Umbraco's controllers entirely - which defeats the purpose of using Umbraco :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top