I recently upgraded from MVC 5 to MVC 3. I never registred a route, however, this URL worked:
http://www.testsite.com/shipworks/index/myemail#yahoo.com?website=testsite.com
Here is my code:
[HttpPost]
public ActionResult Index(string id, string website)
{
string data = string.Empty;
}
I now get a 404 with this code. I tried this route, however, it also fails:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"ShipWorks", // Route name
"{controller}/{action}/{id}/{website}", // URL with parameters
new { controller = "ShipWorks", action = "Index", email = UrlParameter.Optional, website =
UrlParameter.Optional }, new[] { "CloudCartConnector.Web.Controllers" }// Parameter defaults
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
What am I doing wrong? I put the shipping route above the default one. Note that my id is a string. The URL works fine with ?id=myemail#myemail.com.
First approach.
According to your path:
"{controller}/{action}/{id}/{website}"
you don't need to specify explicitly "website" property name. Then, you marked in your route that {id} and {website} are separated by slash /, so correct use of your route mask should be http://www.testsite.com/shipworks/index/myemail#yahoo.com/testsite.com.
However, here is one problem - dot symbol . will not be recognized correctly (in the way you want). So if you remove the dot, the path http://www.testsite.com/shipworks/index/myemail#yahoo.com/testsitecom will work.
Second approach.
In order to reach the results you want, you'd better pass e-mail and website as the query parameter, not as the part of the path.
You can use the following route config:
routes.MapRoute(
"ShipWorks", // Route name
"{controller}/{action}/{id}", // URL with parameters
new
{
controller = "ShipWorks",
action = "Index",
id = UrlParameter.Optional
}, new[] { "CloudCartConnector.Web.Controllers" }// Parameter defaults
);
Controller's action:
//[HttpPost]
public ActionResult Index(string email, string website)
{
(...)
return View();
}
And the query string: http://www.testsite.com/shipworks/index?email=myemail#yahoo.com&website=testsite.com.
Please note also, that since you marked your Index method with [HttpPost] attribute, you will get 404 using GET method (like typing in browser) even if you have correct URL.
Related
I have the following route table:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "UserRoute",
url: "{username}",
defaults: new { controller = "User", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
so, when we have url like : http://mysite/abcde it calls UserController, action Index, if we have url like : http://mysite/dashboard/Index it calls DashboardController, action Index. Ok. But when I try to call the following:
return RedirectToAction("Index", "Dashboard");
It calls UserController, action Index with username parameter equals "Dashboard". Why and how to solve?
Your routing is correct (at least for the URLs you provided). But you are not calling the redirect correctly.
When you generate an outgoing route, it doesn't match a URL, it matches the route values that are passed. Your UserRoute contains 3 route values:
username
Controller
Action
So, in order to generate a URL (or redirect) based on this route, you need to pass all 3 parameters.
return RedirectToAction("Index", "Dashboard", new { username = "Fred" });
That said, MVC will automatically reuse route values if they are in the current request. So, if your route already has a username value (for example, you are already at the URL /Fred), it will be able to match the route without specifying the route value explicitly.
return RedirectToAction("Index", "Dashboard");
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 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 }
);
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 am trying to create another controller for my Ajax handler - so now I have an AppController (The site controller) and an AjaxController (the Ajax request handler).
The problem is, that when I access http://LocalHost:82/Ajax , I get The resource cannot be found. When I access http://LocalHost:82/Ajax/Index , it works.
The problem is the default routing, right? Here is my routing:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "App", action = "NewRequests", id = UrlParameter.Optional } // Parameter defaults
);
If you need more info dont hesitate to ask. Thanks!
Your routing:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "App", action = "NewRequests", id = UrlParameter.Optional } // Parameter defaults
);
Declares that default action is NewRequests, so it is expected that your AjaxController would have [HttpGet] NewRequests actions. You can do that by,
[HttpGet]
public ActionResult NewRequests()
{
// ...
}
or
[HttpGet, ActionName("NewRequests")]
public ActionResult WhatEverNameOfActionYouLike()
{
// ...
}
Is there an NewRequests method returning an ActionResult in the Ajax controller? If not, this makes sense as your default action is NewRequests.