user1269016
user1269016

Reputation:

Routing issues MVC

I am in the process of learning MVC, and currently looking at routing.

I have the following issue: Here is my RegisterRoutes method:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute("Customer", "{controller}/{action}/{objCustomer}",
            new {controller = "Customer", action = "CreateCustomer", id = UrlParameter.Optional});
}

If I ran my application, should hxxp://localhost:12454/ not display the View called by CreateCustomer action in the CustomerController, in other words, the URL should like this? hxxp://localhost:12454/Customer/CreateCustomer

NOTE: I replaced http with hxxp, to not try and create a link

What am I not understanding correctly here?

Here is my whole Global.asax.cs class.

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute("Customer", "{controller}/{action}",
              new { controller = "Customer", action = "CreateCustomer", UrlParameter.Optional});
    }
}

And here is my CustomerController:

public class CustomerController : Controller
{
    // GET: Customer
    public ActionResult ShowCustomer(Customer objCustomer)
    {
        return View(objCustomer);
    }

    public ActionResult CreateCustomer()
    {
        return View();
    }
}

Upvotes: 0

Views: 50

Answers (1)

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Instead of 'id' you are using objCustomer in your routes then you have to specify objCustomer as optional route parameter.

Modify routes as shown below :

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute("Customer", "{controller}/{action}/{objCustomer}",
        new {controller = "Customer", action = "CreateCustomer", objCustomer = UrlParameter.Optional});
}

Make all the custom routes inside routeconfig.cs file inside AppStart folder and don't forget to put this custom route above the default route.

Upvotes: 1

Related Questions