0

I have an app that is just one controller and one action, but I want to pass two values into that action. The end result that I'm looking for is a url that looks like this http://www.example.com/parameter1/parameter2

So I was thinking that the routing would look like this

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

and the controller would look like this

public class HomeController : Controller
{
    public ActionResult Index(string id, string name)
    {
        return View();
    }
}

But I'm clearly wrong as it doesn't work. Does anyone know if it's possible under the index action?

Just to clarify, I want 2 parameters in the default action. I'm aware it's possible by having something like http://www.example.com/books/parameter1/parameter2/ but I specifically want http://www.example.com/parameter1/parameter2/

Roffers
  • 691
  • 1
  • 8
  • 16
  • possible duplicate http://stackoverflow.com/questions/2246481/routing-with-multiple-parameters-using-asp-net-mvc – joetinger Dec 10 '14 at 19:55

3 Answers3

2

To totally omit the controller and action placeholders in the route you can just remove them. (Do not remove it from your default route, better create a new one and place it about the default one)

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

This route will only work with Index action from HomeController but not with others.

Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50
1

If id is optional, what your URL would look like when it's not entered, but name is?

/Home/Index//name 

That's obviously invalid.

Consider using the values in the query string instead of part of the URL.

mellis481
  • 4,332
  • 12
  • 71
  • 118
0

I used this and this to solve the problem. Need two Routes and make sure these routes come above the default MVC route:

 routes.MapRoute(
        name: "with-name",
        url: "Home/{action}/{id}/{name}",
            defaults: new { controller = "Home", action = "Index"}
        //No Optional
        );

routes.MapRoute(
            name: "without-name",
            url: "Home/{action}/{id}",
            defaults: new { controller = "Home", action = "Index"}
        );
Community
  • 1
  • 1
Nima Marashi
  • 121
  • 5