I am trying to setup a map routing using the Web.Routing and Web.MVC. The issue is that I need to be able to grab a potion of an incoming URL so an i can re route the user. i have my MapRoute url grabbing the entire string but since the url has a ? within it, it does not grab the entire string. More specifically, it does not grab anything after the occurrance of the ?.
Is there any way to get past this?
Here is my maproute:
routes.MapRoute(
name: "OldEmailLink",
url: "{tag}",
defaults: new { controller = "ApIssues", action = "Task", id = UrlParameter.Optional }
);
When I debug this, I can get redirected to the action just that the string value of tag is:
default.asp
When tag should be:
default.asp?etaskid=32698
Given this url:
http://localhost1853:/accounting/ap/default.asp?etaskid=32698
Try this for the controller.
public class ApIssuesController : Controller
{
public ActionResult Task(Int32 etaskid)
{
}
}
And this as the Route Config
routes.MapRoute(
name: "OldEmailLink",
url: "accounting/ap/default.asp",
defaults: new { controller = "ApIssues", action = "Task", id = UrlParameter.Optional }
);
Related
In an ASP.NET MVC 5 web application, there is a RouteConfig class that registers many routes. In all of the examples I have seen so far, only the "Default" route has a non-empty name. The URL pattern and default route values seem to be sufficient to correctly associate any URL to the controller and action to execute. So, is there any benefit to naming a route? For debugging or logging? Just for self-documenting the code?
For example:
public class RouteConfig
{
public static void RegisterRoutes( RouteCollection routes )
{
routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );
// Most pages.
routes.MapRoute( name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "home", action = "index", id = UrlParameter.Optional }
// A special page.
// Should the route have a name?
routes.MapRoute( name: "",
url: "special",
defaults: new { controller = "special", action = "index", HttpVerbs = HttpVerbs.Get } );
}
}
The main reason to name a route is so that if you need a link to a route from somewhere in the app, you can reference the name. That way if the actual URL/path changes you don't break everywhere in the code that references that route.
I couldn't get any good information on how to define a route to a contrete action in the selected controller. MSDN doesn't provide clean information on this. There is a mention of action parameter but it doesn't seem to be working.
What I want to achive is to route path like /vehicles/check*** to Check method in the VehiclesController.
A concrete invokation is /vehicles/check?licencePlate=XYZ =>
VehiclesController -> Check(string licenePlate)
I have this map but it does not work:
config.Routes.MapHttpRoute("VehicleTransactions", "Vehicles/Check",
new { controller = "Vehicles", action= "Check" });
Can it be done with MVC?
Thanks, Radek
MapHttpRoute is used for mapping Web API routes. For MVC Controller routes we tend to use MapRoute
So Assuming
public class VehiclesController : Controller {
public ActionResult Check(string licenePlate) {
//...
return View();
}
}
The route would be mapped to
routes.MapRoute(
name: "VehicleTransactions",
url: "vehicles/check",
defaults: new { controller = "Vehicles", action= "Check" }
);
Try this:
routes.MapRoute(
name: "VehicleTransactions",
url: "Vehicles/Check/{licencePlate}",
defaults: new { controller = "Vehicles", action = "Check", licencePlate = UrlParameter.Optional });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
Set "VehicleTransactions" routing before of "Default" routing, because otherwise "Default" overwrite the other.
Special routes is set always before default routing.
I am trying to pass 3 parameters, one int, and 2 datetime to a controller with no luck. I have created custom Routes, but no matter what I do it never connects.
In My View I have
#Html.ActionLink("Check Availability", "Check", new { id = item.RoomID, AD = ArrivalDate.Date.ToString("dd-MM-yyyy"), DD = DepartureDate.Date.ToString("dd-MM-yyyy") }, null)
In my Controller I have
[RoutePrefix("RoomInfoes")]
[Route("Check/{ID},{AD},{DD}")]
[HttpPost]
public ActionResult Check(int? id, string AD, string DD) {
I have tried numerous arrangements of routes and views, but never can connect.
The code above returns a 404 with
Requested URL: /RoomInfoes/Check/1,06-11-2014,06-11-2014
Thanks
Before you use attribute routing make sure you have it enabled:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(); // add this line in your route config
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
then decorate your action like this:
[Route("RoomInfoes/Check/{ID},{AD},{DD}")]
public ActionResult Test(int? id, string AD, string DD)
The RoutePrefix has been removed because it can be used only on class declaration (the code will even doesn't compile). I removed the HttpPost attribute because I assumed that you want make a GET instead of POST.
then to generate a link pointing to this action you can simply write:
#Html.ActionLink("test", "Test", "Home", new { id = 5, AD="58", DD = "58" }, null)
the result will be:
test (the commas in your url will be url encoded)
Do also have the Check Action method for serving HttpGet requests? If not, you will get 404 error.
Have you also done the routes.MapRoute in the RouteConfig.cs? This is required to render the correct URL with #Html.ActionLink helper method.
Try adding below code in RouteConfig.cs, if not already exists.
routes.MapRoute(
name: "RoomInfoes",
url: "Check/{ID},{AD},{DD}",
defaults: new
{
controller = "RoomInfoes",
action = "Check",
ID = UrlParameter.Optional,
AD = UrlParameter.Optional,
DD = UrlParameter.Optional
}
);
You don't Need Route and the RoutePrefix attribute on the Action method.
I am trying to set up custom routing with the following mapped route
edit: my full route config
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
#region FixtureAdmin
routes.MapRoute(
name: "FixtureEdit",
url: "{controller}/{action}/{id}",
defaults: new { controller = "FixtureAdmin", action = "Edit", id = UrlParameter.Optional }
);
#endregion
#region Results
routes.MapRoute(
name: "ResultAdd",
url: "{controller}/{action}/{fixtureId}",
defaults: new { controller = "Result", action = "Add", fixtureId = UrlParameter.Optional }
);
#endregion
And my controller code
public ActionResult Add(int fixtureId)
{
// return model to view etc..
}
This is coming up with the exception, even though I have specified the parameter as optional.
The parameters dictionary contains a null entry for parameter 'fixtureId'
The strange thing is, if I change the parameter of the Add action to just 'Id' then the following URL will work Result/Add/1. I'm confused, is there some default routing that is overriding my custom one? Why would changing the parameter to just 'Id' work?
Edit
Just to test, I added another parameter to the action
public ActionResult Add(int? fixtureId, int? testId)
I then edited the route accordingly and now it works, so I reckon it is an issue with default routing.
Use a nullable int in your Controller Action.
public ActionResult Add(int? fixtureId)
{
// return model to view etc..
}
But the question is, if that is indeed an ID, how would it react if a null/blank ID is requested by the user? Is that ID a key in your DB? You can make it nullable if you are able to handle or provide a default page if the ID is blank/null.
EDIT:
This is because ASP.NET will assume that an unidentified parameter in your request is the id, in your case, Results/Add/1, 1 is unidentified. If you want to make that code work with using fixtureId, you should use Results/Add?fixureId=1. So ultimately, it's not because of the routing, but instead, it's because of the parameter in the Action that you have.
EDIT2:
Also, what you are experiencing there is called a routing conflict. Your routes are conflicting with the Default. You can try to apply constraints.
2,
from your post i think your problem is putting your custom route after default, like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
name: "ResultAdd",
url: "{controller}/{action}/{fixtureId}",
defaults: new { controller = "Home", action = "Add", fixtureId = UrlParameter.Optional }
so:
1/ exception "The parameters dictionary contains a null entry for parameter 'fixtureId'" will come if you dont give the specific route name for any action link or route form because MVC will use default route to routing. So you need to give specific route name to your custom route can be worked, like this:
#Html.ActionLink("Test custom Route", "Add", "Home", new { fixtureId = 1 }, "ResultAdd")
Cheer
Look at this method of adding what the developer calls a 'NullableConstraint' clicky link So if the optional parameter is supplied you can do some checking on it's value.
And also look at the answer following the accepted answer for what seems a simpler, cleaner solution.
I'm trying to setup a custom route in ASP.NET MVC 4. I want my route accessible via
http://www.mydomain.com/high-school/student/1
In an attempt to setup this route, I've added the following in RouteConfig.cs
routes.MapRoute(
name: "HSStudentProfile",
url: "high-school/student",
defaults: new { controller = "Students", action = "HSStudentProfile" }
);
StudentsController.cs
public class StudentsController : Controller
{
public ActionResult HSStudentProfile()
{
return View("~/Views/Shared/Course/Index.cshtml");
}
}
If I visit the url mentioned above, I get a 403.14 error. If I update the route config to use
routes.MapRoute(
name: "HSStudentProfile",
url: "{controller}/high-school/student",
defaults: new { controller = "Students", action = "HSStudentProfile" }
);
It works, however, I have to change the URL path to
http://www.mydomain.com/Students/high-school/student/1
Is there a way to do this without having to have {controller} in my RouteConfig?