2

I'm having difficulty using a constraint on a custom route. The following is my class RouteConfig.cs

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

            routes.MapRoute(
                name: "produtos",
                url: "produtos/{action}/{id}",
                defaults: new { controller = "Produto", action = "Listar", id = UrlParameter.Optional },
                constraints: new { id = @"\d+" }
            );

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

and the following is my Controller 'Produto'

public class ProdutoController : Controller
    {

        MozitMVCContext _context = new MozitMVCContext();

        [HttpGet]
        public ActionResult Cadastrar()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Cadastrar(Produto produto)
        {
            if (ModelState.IsValid)
            {
                _context.Produtos.Add(produto);
                _context.SaveChanges();

                return RedirectToAction("Cadastrar");
            }

            return View(produto);
        }

        [HttpGet]
        public ActionResult Alterar(int id)
        {
            var produto = _context.Produtos.Find(id);
            return View(produto);
        }

        [HttpPost]
        public ActionResult Alterar(Produto produto)
        {
            if (ModelState.IsValid)
            {
                _context.Produtos.Attach(produto);
                _context.Entry(produto).State = EntityState.Modified;
                _context.SaveChanges();
                return RedirectToAction("Listar");
            }

            return View(produto);
        }

        public ActionResult Listar()
        {
            var produto = _context.Produtos.ToList();

            return View(produto);
        }

        public ActionResult Detalhes(int id)
        {
            var produto = _context.Produtos.Find(id);
            return View(produto);
        }

        public ActionResult Excluir(int id)
        {
            _context.Produtos.Remove(_context.Produtos.Find(id));
            _context.SaveChanges();
            return RedirectToAction("Listar");
        }

    }

I want to restrict the user to enter a different one number digit, however when I put the constraint [constraints: new {id = @"\d+"}] my URL ends up taking the 'Default' route, why does this happen? (I'm new to MVC, I do not understand much about routes).

I'm trying to follow a video course and make my code work, I include an Image: (sorry for quality of image, print of video)

Routes

3
  • do you have spaces in your constraints? it should be \d+ without spaces (might just be formatting here, so just asking) Commented Dec 8, 2013 at 4:28
  • Yeah, is formatting something. :\ - constraints: new {id = @"\d+"} Commented Dec 8, 2013 at 4:31
  • write url which goes on default route Commented Jan 17, 2014 at 12:12

2 Answers 2

0

For a simpler scenario like this, you can use such Regex pattern. It will work.

But, to get proper hold on constrain especially when using custom constraints, you should create your own Constraint by inheriting IRouteConstraint inteface

public class MyRouteConstratint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            //Logic goes here
            return true;
        }
    }

And in RouteConfig register it like following,

 routes.MapRoute(
                name: "produtos",
                url: "produtos/{action}/{id}",
                defaults: new { controller = "Produto", action = "Listar", id = UrlParameter.Optional },
                constraints: new MyRouteConstratint()
            );

Hope helps.

Sign up to request clarification or add additional context in comments.

Comments

0

This issue is also discussed in ASP.NET MVC: Route with optional parameter, but if supplied, must match \d+

The short answer is: use this constraint pattern: id = @"\d*".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.