Why we use routing in asp.net mvc - asp.net-mvc

why use custom routing in asp.net MVC
for example
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Enable Routing
routes.MapMvcAttributeRoutes();
//custom route for about page
//routes.MapRoute(
// name:"about",
// url: "Home/About",
// defaults: new { controller = "Home",action= "About", id=UrlParameter.Optional}
// );
//custom route for contactus page
//routes.MapRoute(
// name: "about",
// url: "Home/ContactUs",
// defaults: new { controller = "Home", action = "ContactUs", id = UrlParameter.Optional }
// );
//default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
HomeController.cs
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
//[Route("Home/About")]
public ActionResult About()
{
return View();
}
//[Route("Home/ContactUs")]
public ActionResult ContactUs()
{
return View();
}
}
Index.cshtml
IndexPage
About.cshtml
AboutPage
Contactus.cshtml
ContactusPage
when I run the project then write the URL manually then also give output then why use the routing attribute
home/index
home/about
home/contactus
I comment the route attribute and custom route code and above URL give the proper output then why use route attribute
my question is without route attribute easily run the action method then why need to use route attribute above the controller

If you are happy with the default routes, then you don't need to use the route attributes, or put any custom routes in the RouteConfig.
You can add routes to customise how users get to your pages, either through parameters for more dynamic pages, or to make page urls more friendly - for example:
//make about us page url "/about"
routes.MapRoute(
name:"about",
url: "about",
defaults: new { controller = "Home",action= "About"}
);
//make a product page expect an id param in the url
//for example "/catalog/product/pid1"
//"/catalog/product/pid2"
//"/catalog/product/pid3"
//"/catalog/product/pid4" all match this route
routes.MapRoute(
name:"product",
url: "catalog/product/{productId}",
defaults: new { controller = "Catalog",action= "Product"}
);
The same can be achieved in route attributes:
[Route("about")]
public ActionResult AboutUs()
{
return View();
}
[Route("catalog/product/{productId}")]
public ActionResult GetProduct(string productId)
{
//Get product, build view data etc...
return View();
}

Related

Why does web root give a 404 in ASP.Net MVC 5

I have an ASP.Net MVC 5 site where I changed the routes in the Home controller to remove the Home portion.
My Home Controller looks like
[Route("Index")]
public ActionResult Index()
{
ViewBag.Title = "Home";
ViewBag.Current = "Home";
return View();
}
This works great when I go to http://localhost:29033/Index but when I go to http://localhost:29033 I get the following error:
A public action method 'Index' was not found on controller 'MyProject.Controllers.HomeController'.
My RegisterRoutes looks like:
public static void RegisterRoutes(RouteCollection routes)
{
routes.LowercaseUrls = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("elmah.axd");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Any help would be appreciated.
Given that it appears that attribute routing is being employed here I believe you need to update your routes to get the desired behavior
[RoutePrefix("home")]
public class HomeController : Controller {
[Route("Index")] // Matches GET home/index
[Route("~/", Name = "root")] //Matches GET /
public ActionResult Index() {
//...code removed for brevity
}
}
Reference Attribute Routing in ASP.NET MVC 5

Dealing with multiple custom routes in MVC

I have my Home controller set up like this, going into different functions depending on the parameters it recieves.
Problem is in my home controller, it treats "gametwo" as a query for my route on my home controller.
Example
mysite.com/serchsomething <-- This will search the given string
mysite.com/gametwo <-- This also searches instead of going to gametwo controller
I have normal routeconfig.cs file, with just added attributeroutes.
What is the best way of dealing with routes with multiple parameters? So that they wont be ambigious or crash with any other routes? thanks
home controller
public ActionResult Index()
{
...
}
[HttpGet]
[Route("{Query}")]
public ActionResult Index(string Query)
{
...
}
[HttpGet]
[Route("{Query}/{Version}")]
public ActionResult Index(string Query, int Version)
{
...
}
GameTwo controller
[Route("GameTwo")]
public ActionResult Index()
{
return View();
}
routeconfig
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional }
);
}
Try this above
Home Controller
[HttpGet]
public ActionResult serchsomething(string Query)
{
//do something
}
Game Two Controller
public ActionResult Index()
{
return View();
}
Routing
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
/*serchsomething action*/
routes.MapRoute(
name: "Your route name 1",
url: "serchsomething/{Query}",
defaults: new
{
controller = "home",
action = "serchsomething"
}
);
/*GameTwo Controller*/
routes.MapRoute(
name: "Your route name 2",
url: "GameTwo",
defaults: new
{
controller = "GameTwo",
action = "Index"
}
);
/* default*/
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}}
Are you giving correct controller name?. I am just seeing your url as
mysite.com/gametwo
but controller name as GameTwo Pls change it as GameTwo and try again.

How to display only name in url instead of id in mvc.net using routing

I am getting url like http://localhost:49671/TestRoutes/Display?f=hi&i=2
I want it like http://localhost:49671/TestRoutes/Display/hi
I call it from Index method.
[HttpPost]
public ActionResult Index(int? e )
{
// return View("Display", new { f = "hi", i = 2 });
return RedirectToAction("Display", new { f = "hi", i = 2 });
}
Index view
#model Try.Models.TestRoutes
#using (Html.BeginForm())
{
Model.e = 5 ;
<input type="submit" value="Create" class="btn btn-default" />
}
Display Action method
// [Route("TestRoutes/{s}")]
public ActionResult Display(string s, int i)
{
return View();
}
Route config file
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new { controller = "TestRoutes", action = "Display", s = UrlParameter.Optional, i = UrlParameter.Optional
});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional
});
You need to change your route definition to
routes.MapRoute(
name: "Professional",
url: "TestRoutes/Display/{s}/{i}",
default: new { controller = "TestRoutes", action = "Display", i = UrlParameter.Optional }
);
so that the names of the placeholders match the names of the parameters in your method. Note also that only the last parameter can be marked as UrlParameter.Optional (otherwise the RoutingEngine cannot match up the segments and the values will be added as query string parameters, not route values)
Then you need to change the controller method to match the route/method parameters
[HttpPost]
public ActionResult Index(int? e )
{
return RedirectToAction("Display", new { s = "hi", i = 2 }); // s not f
}
change your route as
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{name}", // URL with parameters
new
{
controller = "TestRoutes",
action = "Display"
} // Parameter defaults
);
and your action as
public ActionResult Display(string name)
{
//action goes here
}
Remove the maproute code:
routes.MapRoute(
"Professional", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new { controller = "TestRoutes", action = "Display", s = UrlParameter.Optional, i = UrlParameter.Optional
});
Use attribute routing code:
[Route("TestRoutes/{s}/{i?}")]
public ActionResult Display(string s, int? i)
{
return View();
}
You can also try using Attribute Routing. You can control your routes easier with attribute routing.
Firstly change your RouteConfig.cs like that:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
//);
}
}
After that change your controller files like that:
namespace YourProjectName.Controllers
{
[RoutePrefix("Home")]
[Route("{action}/{id=0}")]
public class HomeController : Controller
{
[Route("Index")]
public ActionResult Index()
{
return View();
}
[Route("ChangeAddress/{addressID}")]
public ActionResult ChangeAddress(int addressID)
{
//your codes to change address
}
}
You can also learn more about Attribute Routing in this post:
https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/
Another way to solve this problem is to put the proper route before the default route, as follows:
routes.MapRoute(name: "MyRouteName", url: "Id", defaults: new { controller= "Home", action = "Index",id= Id });
Default route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{Id}",
defaults: new { controller = "Home", action = "Index",id= Id }
);

Asp.Net MVC 4 routing and link generation

In ASP.NET MVC 4 I wonder about the behavior, how links are generated for me.
Imagine a simple controller with 3 actions, each taking an integer parameter "requestId", for example:
public class HomeController : Controller
{
public ActionResult Index(int requestId)
{
return View();
}
public ActionResult About(int requestId)
{
return View();
}
public ActionResult Contact(int requestId)
{
return View();
}
}
and this registered route (before the default route):
routes.MapRoute(
name: "Testroute",
url: "home/{action}/{requestId}",
defaults: new { controller = "Home", action = "Index" }
);
I call my index-view using http://localhost:123/home/index/8
On this view, I render links for the other two actions:
#Html.ActionLink("LinkText1", "About")
#Html.ActionLink("LinkText2", "Contact")
Now I expect MVC to render this links including the current route-value for "requestId", like this:
http://localhost:123/home/about/8
http://localhost:123/home/contact/8
But i get these links (without the paramter):
http://localhost:123/home/about
http://localhost:123/home/contact
...but not for the index-action if i would specify one:
#Html.ActionLink("LinkText3", "Index")
What I want to avoid is to explicitly specify the parameters in this manner:
#Html.ActionLink("LinkText1", "Contact", new { requestId = ViewContext.RouteData.Values["requestId"] })
When I move the requestId parameter before the action paramter it works like I expect it, but I don't want to move it:
routes.MapRoute(
name: "Testroute",
url: "home/{requestId}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
Can someone explain me this behavior? How can I get this to work without specifying the parameter explicitly?
InController:
Replace the int to nullable int
For Routing:
set requestId as optional in routing
routes.MapRoute(
name: "Testroute",
url: "home/{action}/{requestId}",
defaults: new { controller = "Home", action = "Index" ,requestId=RouteParameter.Optional }
);

Parameter value not passed in ASP.NET MVC route

I'm learning about creating custom routes in ASP.NET MVC and have hit a brick wall. In my Global.asax.cs file, I've added the following:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
}
The idea is for me to able to navigate to http://localhost:123/home/filter/mynameparam. Here is my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Filter(string name)
{
return this.Content(String.Format("You found me {0}", name));
}
}
When I navigate to http://localhost:123/home/filter/mynameparam the contoller method Filter is called, but the parameter name is always null.
Could someone give a pointer as to the correct way for me to build my custom route, so that it passes the name part in the url into the name parameter for Filter().
The Default route should be the last one.
Try it this way:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
I believe your routes need to be the other way round?
The routes are processed in order, so if the first (default, OOTB) route matches the URL, that's the one that'll be used.

Resources