Dipal Mehta
Dipal Mehta

Reputation: 462

Asp.net mvc action having dynamic in parameter

Masters,

I've defined few routes as follow.

routes.MapRoute(
            name: "Default1",
            url: "{a}",
            defaults: new { controller = "Home", action = "Index" }
        );

        routes.MapRoute(
            name: "Default2",
            url: "{a}/{b}",
            defaults: new { controller = "Home", action = "Index" }
        );

        routes.MapRoute(
            name: "Default3",
            url: "{a}/{b}/{c}",
            defaults: new { controller = "Home", action = "Index" }
        );

        routes.MapRoute(
            name: "Default4",
            url: "{a}/{b}/{c}/{d}",
            defaults: new { controller = "Home", action = "Index" }
        );

and in HomeController,

public ActionResult Index(dynamic data)
{
       return View();
}

I set a break-point at begining of Index method Now, when i hit URL like : http://{MylocalIP:port}/a/b sticks on break point. but I am unable to extract route values that is a & b.

How can we do this? Please help.

Thanks in advance

Upvotes: 3

Views: 2931

Answers (3)

Papa Ccompis
Papa Ccompis

Reputation: 574

I had a similar requirement of an action and a dynamic number of parameters. In my case, I needed to include a folder path as part of the URL. This path can include different number of sub-folders. MVC would interpret the sub-folders as parameters. I found a way to solve this in this article by Bipin Joshi.

I wrote my route this way:

routes.MapRoute(
    name: "Portfolio",
    url: "Portfolio/{*id}",
    defaults: new { controller = "Portfolio", action = "Index", id = UrlParameter.Optional },
    constraints: new { httpMethod = new HttpMethodConstraint("GET") }
);

I used a hard coded "Portfolio" because this route only affects that controller. You can make your route dynamic with :

    url: "{controller}/{*id}"

I built the controller this way:

public class PortfolioController : Controller
{     
    public ActionResult Index(string id)
    {
        //Get Pictures from folder 'id'
    }
}

You can check the results here.

Upvotes: 0

Francis
Francis

Reputation: 1244

The modelbinder doesn't know what to do with a dynamic action parameter. The closest that I'm aware of is JObject, in JSON.net.

You will still have to figure out what what type you have received, deserialize it, and return the appropriate view.

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Even if you manage to get this to work you would have to case your controller action to handle the different parameter. Why not just create different actions depending on the number of parameters and avoid such usage altogether. If you are trying to provide properties of a Model that may not always have values then create a Model and instead of passing dynamic pass the Model to the action.

Upvotes: 1

Related Questions