asp.net mvc routing - Multiple Parameters - asp.net-mvc-3

I've just started MVC and I can pass through an ID to a page but can't seem to get my routing to work with two parameters. Does anyone have any ideas why?
Here is my code:
Global:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);
routes.MapRoute(
"EditVoucher", // Route name
"{controller}/{action}/{id}/{userid}", // URL with parameters
new { controller = "Admin", action = "EditVoucher", id = "", userid = "" } // Parameter defaults
);
**My controller:**
[HttpGet]
public ActionResult EditVoucher(int ID, int UserID)
{
}
**my link:**
#Html.ActionLink("[Edit]", "EditVoucher", new { Controller = "Admin", id = item.ID, userid = 2 })
this passes through the values fine but I end up with this sort of URL:
**/Admin/EditVoucher/2?userid=2**
thanks

ActionLink will use the first route that can satisfy your parameters.
Since the first (default) route also satisfies your parameters, you need to put the custom route first.

Related

How to remove HOME from the url for action results other than Index

How can I replicate this default MVC route code below but to work with multiple ActionResults that are in the home controller. I want them to work just like Index where you do not need /Home/Index in the url to hit example.com/index
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I would like to hit example.com/about and example.com/contact without needing the the controller name in the beginning.
I have tried adding that same code but replaced Index with another action method and it works but it doesn't allow you to have more than 1 existing in this structure at the same time.
Solution?
Ok so I think I got it to work after reading this thread:
ASP.NET MVC - Removing controller name from URL
In the RouteConfig I added the following right before the default route:
routes.MapRoute(
"Root",
"{action}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { isMethodInHomeController = new RootRouteConstraint<HomeController>() }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Then inside of the Controller whos name you are trying to remove from the URL you need to add this:
public class RootRouteConstraint<T> : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name.ToLower());
return rootMethodNames.Contains(values["action"].ToString().ToLower());
}
}
Now if I go to example.com/about , it works and I don't have to use example.com/Home/About

Ajax Sorting and Filtering Is Not Working in MVC

On each index view page which contain list, I'm using ASP.NET MVC AJAX to sort and filter the list. The list is in the partial view. Everything looks so fine until I have a view with a parameter (reference key/FK)
I don't add any routes, just using the default route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
so the url is http://localhost:49458/TimeKeeper/New?billingID=7. If the url in that format, the AJAX sort and filter are not working. I tried to add a new route:
routes.MapRoute(
name: "TimeKeeperNew",
url: "TimeKeeper/New/{billingID}",
defaults: new { controller = "TimeKeeper", action = "New", billingID = "" }
);
so the url become: http://localhost:49458/TimeKeeper/New/7.
Now, the ajax sort and filter are working.
Is there anyone can explain me, what's the problem? Did I use the correct way (by adding a new route) or is there any other way?
I don't even understand why you are saying primary key as MVC has no concept of this.
With only (assuming for the duration of this answer until the break):
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional }
);
Any route that does not define id will be appended to the url with the value.
Url.Action("New", "TimeKeeper", new { billingID = 7 })
Always will produce
http://localhost:49458/TimeKeeper/New?billingID=7
Because "billingID" != "id"
So your options are another MapRoute which I would not recommend, or use Id:
Url.Action("New", "TimeKeeper", new { id = 7 })
which always produces:
http://localhost:49458/TimeKeeper/New/7
Optionally:
public class TimerKeeperController
{
public ActionResult New(string id)
{
int billingId;
if (!string.TryParse(id, out billingId)
{
return RedirectToAction("BadBillingId")
}
....
}
}
BREAK
What about if there are 2 parameters, let's say billingID and clientGroupID? I don't quite understand routing in depth, could you help me to explain this in the answer?
Now you need another MapRoute:
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{id}/{id2}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional,
{id2} = UrlParameter.Optional }
);
And it is required to be before or after the previous MapRoute because anything that would work for this route will work for the previous route, thus this route will never be called. I can't exactly remember which way it goes at the moment, but if you test it, you'll figure it out quickly.
Then you can have:
http://localhost:49458/TimeKeeper/Copy/7/8
with:
public ActionResult Copy(string id, string id2)
{
....
}
notes
Yes you don't have to use a string and parse the values, you could use constraints on the MapRoute or just use Int and throw errors if someone manually types http://localhost:49458/TimeKeeper/New/Bacon.

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

Can't map route to action mvc3

I'm trying to create a new Route in MVC3 to achieve the link http://localhost/Product/1/abcxyz:
routes.MapRoute(
"ProductIndex", // Route name
"{controller}/{id}/{name}", // URL with parameters
new { controller = "Product", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional } // Parameter defaults
);
And I used Route Link like this:
<li>#Html.RouteLink("My Link", "ProductIndex", new { controller = "Product", id = 10, name = "abcxyz" })</li>
Product Index action:
public ViewResult Index(int id, string name)
{
var product = db.Product.Include(t => t.SubCategory).Where(s => s.SubID == id);
return View(product.ToList());
}
The url render as I expected. But when I click on it, I got a 404 error with message
HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly
UPDATE
I place that Route above Default Route and the URL work fine. But there's a problem occure. My index page http://locahost point directly to Index action of Product controller, but I want it points to Index action of Home controller instead
It's because you have 2 optional parameters in your route and the engine can't work out which one to set the value to. See my answer to a similar issue here
You can create a specific route for your products controller first (with mandatory id) and then have the generic fallback route afterwards.
routes.MapRoute(
"ProductIndex", // Route name
"products/{id}/{name}", // URL with parameters
new { controller = "Product", action = "Index", name = UrlParameter.Optional } // Parameter defaults
);
Try it
routes.MapRoute(
"Default", // Route name
"{controller}/{id}/{name}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional } // Parameter defaults
);
for routing details see this link. In this link every type of routing is discussed.
http://www.codeproject.com/Articles/408227/Routing-in-MVC3

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