Get parameter by url for my controller

Asked

Viewed 40 times

0

I need my controller to get a parameter from a URL (localhost/Check/123456), where 12346 would be the parameter.

I configured the Routeconfig:

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

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

        routes.MapRoute("index", "Check/{id}", new { controller = "Check", action = "Indice", id = UrlParameter.Optional });
    }

Controller:

public class CheckController : Controller
{
    private Check _check;

    public ActionResult Index()
    {
        //_check.NumberOfregistrationUser = Convert.ToInt16(numberOfregistrationUser);
        return View();
    }

    public ActionResult Indice(long numberOfregistrationUser)
    {
        _check.NumberOfregistrationUser = Convert.ToInt16(numberOfregistrationUser);
        return Content(Convert.ToString(_check.NumberOfregistrationUser));
    }
}
  • A question: why ask for the parameter as long and then convert it to short?

  • That I adjusted. I left all as int

  • great, now just change the name of the parameter and go to hug.

1 answer

2


Put the parameter of action with the same name as defined in the route.

public class CheckController : Controller
{    
    public ActionResult Indice(long id) // <- trocar o nome do parâmetro
    {
        _check.NumberOfregistrationUser = Convert.ToInt16(numberOfregistrationUser);
        return Content(Convert.ToString(_check.NumberOfregistrationUser));
    }
}
  • I started debbug, loading the url doesn’t even get this method in the controller.

  • So you have more routes set up and they’re conflicting.

  • Only two, one of them default.

  • Reverse the order of routes in Routeconfig

Browser other questions tagged

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