I'm having an odd issue with routing in a basic ASP/MVC project.
I have a bunch of nav items setup:
<li>Home</li>
<li>Fire</li>
<li>Law Enforcement</li>
<li>Forensics</li>
<li>Reconstruction</li>
They all work fine, except for the third one, labeled law-enforcement.
When I mouse over this item, the URL is: http://localhost:54003/home/law-enforcement
When I mouse over any other item, the URl is: http://localhost:54003/fire
My Controller setup is:
public ActionResult Index()
{
return View();
}
[Route("~/fire")]
public ActionResult Fire()
{
return View();
}
[Route("~/law-enforcement")]
public ActionResult Law()
{
return View();
}
[Route("~/forensics")]
public ActionResult Forensics()
{
return View();
}
[Route("~/reconstruction")]
public ActionResult Reconstruction()
{
return View();
}
And my route config is:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapMvcAttributeRoutes();
routes.MapRoute("Default", "{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}
When I go to the route the URL specifies, ASP responds with a 404 page not found (as it should). If I go to the route that I know it should be, such as localhost/law-enforcement then the correct View is rendered.
Any ideas why ASP is routing this one particular action incorrectly?
The Razor Url.Action(...) cannot refer to the route defined by the [RouteAttribute] on the controller action; instead it needs to refer to the action's name. So changing my Razor syntax to refer to #Url.Action("law", "home") instead of #Url.Action("law-enforcement", "home") solved the issue.
You can keep your url mapping in either of 2 ways as below:
One way is to decorate your actionresult with attribute as below:
// eg: /home/show-options
[Route("law-enforcement")] //Remove ~
public ActionResult Law()
{
return View();
}
As per docs
otherwise
Just add one more configuration in Route.config file
routes.MapRoute("SpecialRoute", "{controller}/{action}-{name}/{id}",
new {controller = "Home", action = "law-enforcement", id = UrlParameter.Optional}
);
Source
Related
I added these routes to RouteConfig.cs
routes.MapRoute(
name: "NewPositiveRelease",
url: "dispatch/{poNumber}/{article}",
defaults: new { controller = "PositiveReleaseItem", action = "Create"});
routes.MapRoute(
name: "Dispatch",
url: "dispatch",
defaults: new { Controller = "Dispatch", action = "Index"});
In the hopes that I could go to this url
locahost:3000/dispatch/4529707272/171112
To execute the Create action in PositiveReleaseItemController. However, when I navigate to that url, I am seeing the error:
A public action method '4529707272' was not found on controller 'MVCQCPage.Controllers.DispatchController'.
Can someone please help me understand why this doesn't work?
Here is the controller:
using SharedLibrary.Models;
using System.Web.Mvc;
namespace MVCQCPage.Controllers
{
public class PositiveReleaseItemController : Controller
{
// GET: PositiveReleaseItem
public ActionResult Index()
{
return View();
}
public ActionResult Create(string poNumber, string article)
{
return View();
}
public ActionResult Insert(PositiveReleaseItem item)
{
return View();
}
}
}
I tried changing the order of the given routes, but with the same outcome. Please let me know if I can add any details which might help.
Thanks
Shouldn't it be:
"PositiveReleaseItem/{poNumber}/{article}",
Instead of:
"dispatch/{poNumber}/{article}",
I was able to resolve this by simply placing my new route mappings at the top of Routeconfig.cs (above all the others).
Not sure why this worked, as none of my other route maps refer to the Dispatch controller, so its weird that it was complaining about that.
This question already has answers here:
Asp.Net Routing - Display complete URL
(3 answers)
Closed 6 years ago.
When i redirect from a Controller using
RedirectToAction("Index", "Controller");
Or Generate a link with UrlHelper
#Url.Action("Index","Controller");
In both ways the "/Index" Part is striped down from my URL.
Although for SEO Purposes i want my url to be displayed always at the same manner.
www.domain.com/en/Controller/Index
but now i get
www.domain.com/en/Controller
How can i force these two methods above always display the "/Index" Part.
P.S I know this happens because "Index" is indicated as a Default action on my route, but either way i want it to be displayed.
Add new role in RouteConfig with before default route with Index action
routes.MapRoute(
name: "DefaultIndex",
url: "{controller}/Index/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Check your configuration inside global.asax file. It can be like this.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Controller", action = "Index", id = UrlParameter.Optional });
}
Maybe based on your mask you always going to default route. So just remove default mapping.
You can try do this:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return RedirectToAction("About","Home");
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
I am learning asp.net MVC and I was trying Redirect to action and I tried the following code and I keep getting Redirect Loop Error.
This is the Controller class in which I am getting an error
public class CuisineController : Controller
{
// GET: Cuisine
public ActionResult Search(string name)
{
return RedirectToAction("About","Cuisine");
}
public ActionResult Index()
{
return Content("This is Index");
}
public ActionResult About()
{
return Content("this is About");
}
}
I have also created a route of my own other than the Default route
routes.MapRoute(name: "Cuisine",
url: "cuisine/{name}",
defaults: new { controller = "Cuisine", action = "Search", name = UrlParameter.Optional });
When I try to access the Cuisine controller it gives me a redirect loop error.
Thank you
In your routeConfig, you have a route defined for "cuisine/{name}" and it will be sent to the Search action method.
In your Search action method, You are redirecting to the About, Which is cuisine/About. This is matching with the route you defined cuisine/{name} so it will send the request to Search action again. The same process will keep running. That is why you are getting the redirect loop
You should either delete this specific route you defined or rename the url pattern for cusine search to prevent the redirect loop.
routes.MapRoute(name: "Cuisine",
url: "searchcuisine/{name}",
defaults: new { controller = "Cuisine", action = "Search",
name = UrlParameter.Optional });
This should be pretty obvious:
routes.MapRoute(name: "Cuisine",
url: "cuisine/{name}",
defaults: new { controller = "Cuisine", action = "Search", name = UrlParameter.Optional })
Says all urls that start with cuisine/ use the Search method on the CuisineController.
/Cuisine/About starts with that url, so it willl always use the Search method.
It looks like you want to make {name} part of URL. You can use attribute routing instead of changing default routing, it does not have such global "destructive" effects (explained in other answers) at least, and looks it's what you are actually after :)
[Route("Search/{name}")]
public ActionResult Search(string name)
{
return RedirectToAction("About", "Home");
}
See more about attribute routing here (for this to work, don't forget to add routes.MapMvcAttributeRoutes() if it is not there yet).
You need to restore controller action pattern. Just change url: "cuisine/{name}" to url: "cuisine/{action}/{name}"
I would like to have an Index action with an optional string parameter. I'm unable to make it work.
I need the following routes:
http://mysite/download
http://mysite/download/4.1.54.28
The first route will send a null model to the Index view, and the second one will send an string with the version number.
How can I define the route and the controller?
This is my route definition:
routes.MapRoute(
name: "Download",
url: "Download/{version}",
defaults: new { controller = "Download", action = "Index", version = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
And this is the controller:
public ActionResult Index(string version)
{
return View(version);
}
Why does this not work? I'm not an expert in ASP MVC but this seems to be a very simple problem.
The error
When I go to http://mysite/downloads it works fine
When I go to http://mysite/downloads/4.5.6, the controller is correctly called, and the parameter is correctly passed. But then seems that the view is not found. This is the error I found:
string? will not work because string is not a value type.
You can set a default value to your parameter:
public ActionResult Index(string version="")
{
return View(version);
}
The issue is fixed passing the parameter to the view in the following way:
public ActionResult Index(string version)
{
return View((object)version);
}
Or
public ActionResult Index(string version)
{
return View("Index", version);
}
When you pass a string model to the view, if the model is a string parameter, it is interpreted as the view name due to the following overload method
View(String viewName)
Your Download route is conflicting with your Default route. Comment out the Download route and it will probably work.
BTW you can install RouteDebugger to figure out these kind of problems for yourself.
Your controller is looking for a view with the same name as the version attribute entered in the url (e.g. 4.1.54.28). Are you intentionally looking for a view with that name, in which case it should be in the Views/Download folder or your project. If however you simply want to pass it to the default view as a variable to be used on the page your best off sticking it in a model or you can just stick it in ViewBag if it's a one off.
Also you don't need to use:
Public ActionResult Index(string version)
You can use routedata instead e.g.
Public ActionResult Index()
{
string version = RouteData.Values["Version"].ToString();
ViewBag.version = version;
return View();
}
Hope this of some help
You are not set action name in url like {action}
you can try:
routes.MapRoute(
name: "Download",
url: "Download/{action}/{version}",
defaults: new { controller = "Download", action = "Index", version = UrlParameter.Optional }
);
I'm pretty sure it's because in the View you state it is an optional parameter, but your controller says that it is mandatory. Change the signature of your index method to expect a nullable param
public ActionResult Index(string? version)
{
return View(version);
}
Why not have two methods in your download controller:
public ActionResult Index()
{
return View();
}
[HttpGet, ActionName("Index")]
public ActionResult IndexWithVersion(string version)
{
return View(version);
}
In my ASP.NET MVC application, I want to use this ASP.NET MVC Attribute Based Route Mapper, first announced here.
So far, I understand how to implement code that uses it, but I've run into a few questions that I think those who have used this attribute-based route mapper in the past will be able to answer.
How do I use it with ActionResults that are for HTTP POSTs? In other words, how does it work with form submissions and the like? Should I just put the URL of the GET method in, or should I use the GET method URL without any parameters (as in HTTP POST they aren't passed in through the URL)?
How do I use it with "URL querystring parameters"? Can the attribute be configured to map to a route such as /controller/action?id=value rather than /controller/action/{id}?
Thanks in advance.
How do I use it with ActionResults
that are for HTTP POSTs?
You decorate the action that you are posting to with the [HttpPost] attribute:
[Url("")]
public ActionResult Index() { return View(); }
[Url("")]
[HttpPost]
public ActionResult Index(string id) { return View(); }
If you decide to give the POST action a different name:
[Url("")]
public ActionResult Index() { return View(); }
[Url("foo")]
[HttpPost]
public ActionResult Index(string id) { return View(); }
You need to supply this name in your helper methods:
<% using (Html.BeginForm("foo", "home", new { id = "123" })) { %>
How do I use it with "URL querystring
parameters"?
Query string parameters are not part of the route definition. You can always obtain them in a controller action either as action parameter or from Request.Params.
As far as the id parameter is concerned it is configured in Application_Start, so if you want it to appear in the query string instead of being part of the route simply remove it from this route definition:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoutes();
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" }
);
}