Search code examples
asp.net-mvcasp.net-mvc-4asp.net-mvc-routing

MapRouting ASP.Net MVC4 - Cant generate new URL's


I have a problem with my MapRouting. I want to generate new URL's with the name from an array list. I am new with MVC and are trying with the experiense from Web app's. I want to generate new links that dont have Action in it. I just want "Localhost/Chat/" + chatName. Please ask me questions if you dont understand sense im not so good at explaining!

        LocalhostHoardeWebService.varShareWS addChatRooms = new LocalhostHoardeWebService.varShareWS();
        Array wsRespnonsAddChatObject = addChatRooms.addAllChatRoomsRoute();



        foreach (string chatNameArray in wsRespnonsAddChatObject)
        {
            string chatName = chatNameArray.ToString();

            routes.MapRoute(
                name: chatName,
                url: "{controller}/{id}",
                defaults: new { controller = "Chat", id = chatName  }
           );

        }

Solution

  • Your misunderstanding how routes work. You need to specify a default controller and action method, and in the action method you pass the value of chatName to a parameter. you route should look like (one route, no loop). Also make sure this is above the Default route.

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

    and in ChatController

    public ActionResult Index(string id)
    {
      // id is the value of chatName
    }
    

    and call it as /Chat/abc or /Chat/xyz