ASP NET MVC Include Url Parameter on all pages

6

I have an ASP NET MVC application that is multi-client and multi-user, that is, it is prepared to be used by multiple clients and each client can have multiple users.

Initially, the login form has the text entry for the client code. However I want to perform some routing so the user can inform the client code directly in the URL, I know that using the default routing I can get this code by taking the value of the id parameter in the controller, however this works only on the first page if some redirection is performed I can not get this information.

How do I implement this? below my RouteConfig class:

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

            routes.MapRoute("Default", "{controller}/{action}/{id}",
                new {controller = "Acesso", action = "Login", id = UrlParameter.Optional});
        }
    }
    
asked by anonymous 03.03.2015 / 18:27

2 answers

4

Assuming you want a url in this pattern:

/empresaId/clientes/clienteId 

That could be translated to:

/1/clientes/10

You can create a route:

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

            routes.MapRoute("Empresa", "{empresa}/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional});

            routes.MapRoute("Default", "{controller}/{action}/{id}",
                new {controller = "Acesso", action = "Login", id = UrlParameter.Optional});
        }
    }

Define the business parameter in the controller:

public class Clientes : Controller 
{
    // rota: /1/clientes/10
    public ActionResult Index(int empresa, int id) 
    { 
    }

    // rota: /1/clientes/editar/10
    public ActionResult Editar(int empresa, int id) 
    { 
    }
}

Create a session for the company id at login:

var empresaId = 1;
Session.Add("empresa", empresaId);

To create the links, you use the session when passing the company parameter:

@Html.Action("index", "clientes", new { empresa = Session["empresa"] })

or

@Html.ActionLink("editar", "clientes", new { empresa = Session["empresa"] })

or

@Url.Action("index", "clientes", new { empresa = Session["empresa"] })
    
03.03.2015 / 19:48
1

I think something like this could solve your problem:

routes.MapRoute("Default", "Cliente/{id}",
            new {controller = "Cliente", action = "Pesquisar", id = UrlParameter.Optional});

Your Controller looks like this:

public class Cliente : Controller 
{
    public ActionResult Pesquisar(int id) // id seria o código do cliente
    { ... }
}

The call would look like this:

  

localhost / Client / 12345

    
03.03.2015 / 19:27