HOW TO ACHIVE MVC ROUTE WITH NUMBERS

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
 802  View(s)
Ratings:
Rate this:

I am trying to route an old URL that is domain.com/1024 to my home page in mvc.

I keep getting resource not found errors.

Here is my routeConfig

        routes.MapRoute(

        name: "1024",

        url: "{controller}/{action}",

        defaults: new { controller = "Home", action = "Direct", id = UrlParameter.Optional }

    );

 

My Controller

 

    public ActionResult Direct()

    {

 

        return RedirectToAction("Index");

    }

  1. Pravesh Singh

    Post:101

    Points:709
    Re: How to achive MVC route with numbers

    Hi jay


    If you have your route definition before the default, for example:

    routes.MapRoute(
      name: "1024",
      url: "{id}",
      defaults: new { controller = "Home", action = "Direct" }
    );

    routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    This will route (host):(port)/ to Index and (host):(port)/1024 to Direct where you can RedirectToAction("Index").

    For example a HomeController to demonstrate the point (This ONLY redirects 1024 to index):

    public class HomeController : Controller
        {
            //
            // GET: /Home/

            public ActionResult Index()
            {
                return View();
            }

            public ActionResult Direct(int? id)
            {
                if (id.HasValue && id.Value == 1024)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    return View();
                }
            }

        }
    This would redirect any id to index:

    public class HomeController : Controller
        {
            //
            // GET: /Home/

            public ActionResult Index()
            {
                return View();
            }

            public ActionResult Direct(int? id)
            {
                return RedirectToAction("Index");
            }

        }

      Modified On Apr-12-2016 12:16:06 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!