Actionresult Dynamic Route

Asked

Viewed 148 times

1

I have two Controllers: College and Course

public class InstituicaoController : Controller
    {
        // GET: Instituicao
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Instituicao(string instituicao) {

            return View();

        }

        public ActionResult Curso() {

            return View();
        }
    }


<a href="@Url.Action("Curso", "?", new {faculdade = "NomeFaculdade", curso = "Nomecurso"})">Detalhe do Curso </a>

What is the procedure to leave this way: www.exemplo.com.br/{School Name}/{Course Name}

  • In fact you have an Institutional Controller that has 3 methods... The URL you want should run which method?

1 answer

0

Log the following route on RouteConfig.cs:

        routes.MapRoute(
            name: "Instituicao",
            url: "{faculdade}/{curso}",
            defaults: new { controller = "Instituicao", action = "Instituicao", faculdade = "", curso = "" }
        );

We’ll have to rule out Instituicao of the standard routes because the route Default is greedy and will try to solve to Instituicao also. Implement the following attribute:

public class NotEqual : IRouteConstraint
{
    private string _match = String.Empty;

    public NotEqual(string match)
    {
        _match = match;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return String.Compare(values[parameterName].ToString(), _match, true) != 0;
    }
}

Modify the route Default for:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.