Calling controller actions using custom routes always directing to same action - ajax

I am accessing different actions which takes different number of parameters but even on applying custom routing the call to the same action is always take place .
Controller data-----
[System.Web.Mvc.ActionName("Details1")]
public string Detail1(string Name)
{
return null;
}
[System.Web.Mvc.ActionName("Details2")]
public string Detail2(string Name, string secondName)
{
return null;
}
custom routes
context.MapRoute(
"M_default",
"controllername/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
context.MapRoute(
"name1",
"controllername/{Name}",
new { controller = "controllername", action = "Details1" }
);
context.MapRoute(
"name2",
"controllername/{Name}/{secondName}",
new { controller = "controllername", action = "Details2" }
);
the forst route is default ,second route is for details1 ,third route is for details2 .
And I calling these from view $.post whose URLS are as
URL for Details1 calling
"/api/controllername/?Name="+somename+"",
URL for Details2 calling
"/api/controllername/?Name="+somename+"&secondName="+othername,
I had taken reference from here
What could be possible solution . Any suggestion , help will be appreciated .

Try putting your default route last. I think it's catching everything.

If I understand correctly, your problem lies in how the rules are parsed by the framework.
You must keep in mind that the framework start from the top of your rules list and go down till one condition is matched. Inverting the sequences of your urls should fix your problem
You can also use this route debugger to check if all your routes are working correctly
Update:
I mean creating the route like this. And I just saw that you are missing the "api" part. Use the route debugger to check that everything is correct.
context.MapRoute(
"name2",
"api/controllername/{Name}/{secondName}",
new { controller = "controllername", action = "Details2" }
);
context.MapRoute(
"name1",
"api/controllername/{Name}",
new { controller = "controllername", action = "Details1" }
);
context.MapRoute(
"M_default",
"controllername/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
That should handle correctly
/api/controllername/somename/someothername
and
/api/controllername/somename

Related

ASP.NET MVC3 Complex Routing Issue

I have a the following default route set up and it works fine:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Here is an example of successful route for me: "/PositionDetail/Candidates/2"
This is all fine and dandy, but the issue I have is that I want to set up a route that goes deeper. i.e. "/PositionDetail/Candidates/2/GetMoreCandidates" and "/PositionDetail/Candidates/2/Resume/3" where the Resume would be another action that I want to perform, and 3 would be ID. Note: Each of these route will load a new page, and not some partial view.
How do I set something up like this, and what would the 'PositionDetail' Controller Look like?
For example, for second task it may be as follows:
public ActionResult Resume(int CandidateID, int ResumeID)
{
return View();
}
In your Routing:
routes.MapRoute(
"Resume", // Route name
"{controller}/Candidates/{CandidateID}/{action}/{ResumeID}", // URL with parameters
new { controller = "PositionDetail", action = "Resume", CandidateID = UrlParameter.Optional, ResumeID= UrlParameter.Optional }
);
For fist task - the same logic

Routing legacy requests with and without querystring

(Before starting: I am aware of this and this. I'd like to find a more concise solution -if possible- for a slightly more specific problem)
I'm rewriting an old Webforms app in MVC. As usual, no permalinks should be broken.
I'm using standard {controller}/{action}/{id} routes. Legacy paths are usually SomePage.aspx?ID=xxx, and I have one particular case where Foo.aspx is a list of Bar (new URL: /Bar or /Bar/Index) and
Foo.aspx?ID=xxx is the Bar detail (new URL: /Bar/View/xxx)
One possible workaround is adding the following before the Default MapRoute:
routes.MapRoute("Bar View", "Foo.aspx",
new { controller = "Bar", action = "View" });
And then defining the corresponding action in BarController:
public ActionResult View(int? id)
{
if (id == null)
return RedirectToAction("Index");
return View();
}
There are two problems with this:
Now, if I create an ActionLink, it uses the legacy format
I'd like to handle this in the routes; making the id nullable and redirecting in the controller is just wrong
I'm fine with mapping the legacy URLs by hand (I don't need a generic solution and there are only about 8 pages)
This is a new project, so I'm not tied to anything.
I was able to solve this based on Dangerous' idea plus a constraint based on this answer.
My new route table is:
routes.MapRoute("Bar", "Bar/{action}/{id}",
new
{
controller = "Bar",
action = "Index",
id = UrlParameter.Optional
});
routes.MapRoute("Bar View", "Foo.aspx",
new {controller = "Bar", action = "View"},
new {id = new QueryStringConstraint()});
routes.MapRoute("Bar Index", "Foo.aspx",
new { controller = "Bar", action = "Index" });
routes.MapRoute("Default", /*...*/);
And the QueryStringConstraint couldn't be simpler:
public class QueryStringConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route,
string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
return httpContext.Request.QueryString.AllKeys
.Contains(parameterName, StringComparer.InvariantCultureIgnoreCase);
}
}
I believe if you specify the following routes:
routes.MapRoute(
null,
"Bar/{action}/{id}",
new { controller = "Bar", action = "View", id = UrlParameter.Optional },
new { action = "Index|Next" } //contrain route from being used by other action (if required)
);
routes.MapRoute(
null,
"Foo.aspx/{id}",
new { controller = "Bar", action = "View", id = UrlParameter.Optional }
);
//specify other routes here for the other legacy routes you have.
Then this should solve your first problem. If the user specifies Foo.aspx in the url then they will be taken to the View action.
If the action link:
#Html.ActionLink("Click me", "Index", "Bar")
is specified then the first route will be used (as the order matters).
However, I could not figure out how to specify if Foo.aspx?id=... then to go to one route else if Foo.aspx is specified then go to the other route. Therefore, I would check whether id is null in the action. However, if you do find this out I would very much like to know.
Hope this helps.

I can't get the #ActionLink to render the correct url to work with my MVC3 default routing

I'm trying to take advantage of the default routing so I get a URL without a query string parameter.
So, I've currently got this url:
http://www.mysite.Items/Edit?ItemID=19719
And I'm trying to get a URL like this:
http://www.mysite.Items/Edit/19719
The routing works, but I can't get the #Html.ActionLink method to produce the 2nd url.
Here is my razor code:
#Html.ActionLink("Edit", "Edit", new {item.ItemID}, new { id = "edit-" + item.ItemID })
The first argument is my link's text. The 2nd argument is the Action. 3rd is the ID Value and finally the last argument is and HTML attribute I use for some javascript I'm using.
Originally I had my 3rd Argument as
new {itemID = itemID}
This was when my Edit action expected an integer value named itemID as the parameter. I changed it to 'id' so the routing would work.
Ideally I would like a route that would pass the 19719 value to an action with the argument named itemID, but this is beyond the scope of this question.
Thanks in advance.
SOLVED
Thanks Darin Dimitrov for this solution.
I ended up leaving my html code and action arguments the way I had them originally. All that was really required was an update to my routes. I should note that I had to add my new route map before the default. Anyway, here is my route registration now that made this all work.
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("", "Items/{action}/{itemID}", new { controller = "Items", action = "Details", itemID = #"\d+" });
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
}
The default routes uses id as route token name, so you want:
#Html.ActionLink(
"Edit",
"Edit",
new { id = item.ItemID },
new { id = "edit-" + item.ItemID }
)
Notice new { id = item.ItemID } and not new {itemID = itemID} and not new {item.ItemID}.

How do I redirect everything to a single controller?

I have three specific routes:
routes.MapRoute(
"Home Page",
"",
new { controller = "Home", action = "Index" }
);
routes.MapRoute(
"Admin Section",
"AdminSection/{action}/{id}",
new { controller = "AdminSection", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Listings",
"{controller}/{action}/{id}",
new { controller = "Listings", action = "Index", id = UrlParameter.Optional }
);
Basically, the first two routes work as planned, however, I want everything that isn't specifically in a route to be redirected to the listings controller.
I am still quite new to routing and have been trying to Google this for the past hour without any luck - I know exactly what is going on here, but, I don't know how to fix it.
I have used RouteDebugger, and I can see that it is hitting the route, but, the issue is that it will only go to the Listings controller if a controller is not specified - but, obviously there will always be something there.
I have tried a few different combinations - I thought I was on to a winner by removing the {controller} part of the URL and still defining the default value, but, I am not having much luck.
Does anyone know what I need to do?
How about this:
routes.MapRoute("Listings", "{action}/{id}",
new { controller = "Listings", action = "Index", id = UrlParameter.Optional });
site.com/test :
It'll go to action: test, controller: listing, id = blank
Edit: As I understand it you want a catch-all route.
http://richarddingwall.name/2008/08/09/three-common-aspnet-mvc-url-routing-issues/
routes.MapRoute("Listings", "{*url}",
new { controller = "Listings", action = "Index" }
);
Original:
I can't test this at the moment but
routes.MapRoute(
"Listings",
"{anythingOtherThanController}/{action}/{id}",
new { controller = "Listings", action = "Index", id = UrlParameter.Optional }
);
This should work.
In your Listings controller, just accept a string parameter "anythingOtherThanController" and it will get bound to it.
The main problem here is that /some/action will be mapped to the same action as /another/action. So I'm not sure what you're trying to do here :)
Provide a default route and provide controller name as listings controller. Keep this route mapping at the bottom of all the mappings.
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Listings", action = "Index", id = UrlParameter.Optional }
);
Sorry I got sequence mixed.

ASP.net MVC RenderAction and Route

I have a web project using ASP.net MVC3. There's an child action in my project. I use
<% Html.RenderAction("Navigator", "Application");%>
to call a shared action. But I find that if my current url is "localhost/application", it throws an exception "No route in the route table matches the supplied values". But when current url is "localhost/application/index", it works fine. Index is a default action in my route config, which is shown below:
public static void RegisterRoutesTo(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
//routes.IgnoreRoute("{*chartName}", new { chartName = #"(.*)?Chart.aspx" }); //ignore request for charting request
routes.Ignore("{*pathInfo}", new { pathInfo = #"^.*(ChartImg.axd)$" });
routes.MapRoute(
"Default", // Route name
"{controller}/{id}/{action}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { httpMethod = new HttpMethodConstraint("GET", "POST") } // Allowed http methods
);
}
Note that I switch default id and action position. I see mvc can remove the default controller and action name in url when using "Html.ActionLink(...)". And I don't like to use explicit url string in my views. How can make it work?
My Action code is simple:
[ChildActionOnly]
public ActionResult Navigator()
{
return PartialView(appFacility.GetAll());
}
Thanks alot.
Wrong route URL definition and defaults combination
The problem is that you can't have non optional parameters after an optional parameter.
Why does localhost/application/index work? This are route values:
controller = "application" (supplied from URL)
id = "index" (supplied from URL)
action = "Index" (supplied as route default)
Basically these values equal to localhost/application/index/index request URL.
If you'd like your RenderAction to work, you'd have to call it this way:
<% Html.RenderAction("Navigator", "Application", new { id = 0 }); %>
which would equal to localhost/application/0/navigator request URL.
But you'll soon find out that your route doesn't work and you'll have to change it (because I suppose you don't like having that additional 0 in your URL). If you provide information how you'd like your route work (or why you've decided to switch action and id) we can provide an answer that will help you meet your requirements.
Optinal parameters work correctly only on the end of route. Try something like this:
routes.MapRoute("DefaultWithID", "{controller}/{id}/{action}",
new { action = "Index" },
new { id = "^[0-9]+$" }
);
routes.MapRoute("Default", "{controller}/{action}",
new { controller = "Home", action = "Index" }
);
edit: hopefully fixed :) this version counts on fact that ID will be numeric - without constraint we can't tell whether it would mean action or id, so there couldn't be default action on routes when ID is specified

Resources