R
R
Roman Gamretsky2014-06-27 23:10:07
ASP.NET
Roman Gamretsky, 2014-06-27 23:10:07

How to implement a route in ASP.net MVC?

Tell me how to implement the following address:
site/{parametr}
That is, it is necessary that the parameter be immediately passed to the Index action and if parametr=index then the main page is displayed, and in other cases another view is loaded

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valery Abakumov, 2014-07-01
@rgamretsky

Good afternoon!
If I understand you correctly, the route would be:

routes.MapRoute(
  name: "",
  url: "site/{parametr}",
  defaults: new { controller = "Home", action = "Index", parametr = "index" }
);

If you need the parameter value to be equal to "index" when requesting the main page of the site (i.e. the user requests, for example, "yoursite.ru"), then the very first route should be the following route:
routes.MapRoute(
  name: "",
  url: "",
  defaults: new { controller = "Home", action = "Index", parametr = "index" }
);

Note that the url is empty. This matches the "/" URL pattern, so this route will work for the root URL of the entire site, i.e. for "yoursite.ru".
For such a route, your action method should look something like this:
public ActionResult Index(string parametr)
{
  if(parametr != null)
  {
    switch(parametr)
    {
      case "index":
        return View();
      default:
        //return RedirectToAction("IndexOther", "Home");
        //или
        return View("IndexOther");
    }
  }	
  // Здесь что-то происходит...
  return View(); 
}

or you can specify a parameter variable with a default value in the action method itself:
public ActionResult Index(string parametr = "index")
{
  switch(parametr)
  {
    case "index":
      return View();
    default:
      //return RedirectToAction("IndexOther", "Home");
      //или
      return View("IndexOther");
  }
  // Здесь что-то происходит...
  return View();
}

To be honest, I have not tested these routes in, so to speak, a production environment. If it doesn't work out for you, then let me know, I'll make a test project, I'll check it.
Hope I could help you.
Good luck!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question