I have the following route defined
routes.MapRoute(
"ItemName",
"{controller}/{action}/{projectName}/{name}",
new { controller = "Home", action = "Index", name = "", projectName = "" }
);
This route actually works, so if I type in the browser
/Milestone/Edit/Co-Driver/Feature complete
It correctly goes to the Milestone controller, the edit action and passes the values.
However, if I try and construct the link in the view with a url.action -
<%=Url.Action("Edit", "Milestone", new {name=m.name, projectName=m.Project.title})%>
I get the following url
Milestone/Edit?name=Feature complete&projectName=Co-Driver
It still works, but isn't very clean. Any ideas?
When constructing and matching routes in ASP.NET routing (which is what ASP.NET MVC uses), the first appropriate match is used, not the greediest, and order is important.
So if you have two routes:
"{controller}/{action}/{id}"
"{controller}/{action}/{projectName}/{name}"
in that given order, then the first one will be used. The extra values, in this case projectName and name, become query parameters.
In fact, since you've provided default values for {projectName} and {name}, it's fully in conflict with the default route. Here are your choices:
Remove the default route. Do this if you don't need the default route any more.
Move the longer route first, and make it more explicit so that it doesn't match the default route, such as:
routes.MapRoute(
"ItemName",
"Home/{action}/{projectName}/{name}",
new { controller = "Home", action = "Index", name = "", projectName = "" }
);
This way, any routes with controller == Home will match the first route, and any routes with controller != Home will match the second route.
Use RouteLinks instead of ActionLinks, specifically naming which route you want so that it makes the correct link without ambiguity.
Just to clear up, here is what I finally did to solve it, thanks to the answer from #Brad
<%=Html.RouteLink("Edit", "ItemName", new { projectName=m.Project.title, name=m.name, controller="Milestone", action="Edit"})%>
You can try
Html.RouteLink("Edit","ItemName", new {name=m.name, projectName=m.Project.title});
Related
As the title says.
I have a route set up and working fine, which provides a default action when none is specified. I just want to hide the action from the URL because it's unnecessary clutter.
Setting the "ActionName" parameter as null, or "", will just result in the current page's action being substituted instead - which doesn't work.
I'm open to using #Html.ActionLink() if that will get me what I need.
My route definition is
routes.MapRoute(
name: "MyBookRoute",
url: "Book/{id}",
defaults: new { controller = "Book", action = "Index" }
);
If all else fails, I suppose I can deal with writing out the hrefs manually, but this should not be a difficult thing for Razor to do.
Has anyone else come across this and knows what to do?
Base on your route definition, then either
#Url.Action("Index", "Book", new { id = 1 })
or
#Html.ActionLink("Your link text", "Index", "Book", new { id = 1 }, null)
will remove the action name from the generated url.
I've looked through the various questions already asked on this topic, and I've spent time trying to get it working how I would like it to, but I haven't had much luck so hopefully someone here can help me fill in the gaps.
With a new site I'm creating I wanted to try getting the URL structure to be more RESTful (I wanted to do it with my first MVC3 creations, but, time did not permit such experimenting). However, I don't want the different URLs to all point to the same action. I want different actions for each resource requested to keep the controller code concise and intuitive.
Here is an example of the URL structure I'm shooting for:
/Case //This currently works
/Case/123 //This currently works
/Case/123/Comment //This one does not work (404)
Here is how I currently have my routes setup:
routes.MapRoute(
"Case",
"Case/{id}",
new { controller = "Case", action = "Number" }
);
routes.MapRoute(
"CaseComment",
"Case/{caseId}/Comment/{id}",
new { controller = "Case", action = "CaseComment" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The first two URL's I listed are worked correctly with this route structure. The first URL takes me to my listing page. When an id is specified, I hit the Number action so I can show details for that particular record. The Comment URL is not working.
I have the action for the third URL defined as:
public ActionResult CaseComment(string caseId, string id) {
//Narr
}
What am I missing? And, could I set this up in an easier fashion for future resources?
I believe MapRoutes are order specfic, so
/Case/123/Comment
is using your
routes.MapRoute(
"Case",
"Case/{id}",
new { controller = "Case", action = "Number" });
route, thus throwing a 404. Most specific route should be place above more general routes.
Try placing the CaseComment route above the Case route.
Mapping routes are order specific.
One thing you may wish to consider for restful routing in MVC is a project called RestfulRouting that is on GitHub originally written by Steve Hodgekiss.
https://github.com/stevehodgkiss/restful-routing
If nothing else, looking at the code may well help you.
Hope this helps.
I needed to make the id parameter optional.
routes.MapRoute(
"Case Resources",
"Case/{caseId}/{action}/{id}",
new { controller = "Case", action = "CaseComment", id = UrlParameter.Optional }
);
I have a route that is working correctly in the form of the standard:
{controller}/{action}/{id}
Example real URL is:
http: //mydomain/Project/Index/PRJ2010001
I would like to remove the "Index" from the URL so that when a user enters:
http: //mydomain/Project/PRJ2010001
...the Index view is still rendered.
Note that my ProjectID's always start with "PRJ"
Questions:
1) How do I register this route in my Global.asax.cs file?
2) How would I generate the correct link (minus the "Index") in my views using Url.Action()?
This is what I tried:
routes.MapRoute(
"View Project",
"Project/{id}",
new { controller = "Project", action = "Index" },
new { id = #"/^PRJ/" } //regex constrains this route to only work if {id} begins with "PRJ"
);
MVC messes with your regex to make sure that the pattern matches the whole value rather than just part. Specifically, it does...
string pattern = "^(" + str + ")$";
return Regex.IsMatch(input, pattern, RegexOptions.CultureInvariant
| RegexOptions.IgnoreCase);
so your regex is tested as ^(/^PRJ/)$, which is nonsense. Passing in "PRJ\\d+" should work.
In this particular case I'd consider dropping the regex and just including PRJ in the URL pattern...
routes.MapRoute(
"View Project",
"Project/PRJ{id}",
new { controller = "Project", action = "Index" }
);
... though your action would then have to deal with receiving an ID without the prefix.
I think the issue might be with your regex. Try simply "PRJ\w+" or "PRJ\d+"
I'd even try it without the regex to make sure everything else works OK.
I am barely starting out with my first project on the ASP.NET MVC project type and I am creating a Details page where instead of passing the templated (int id), I would like to pass a string instead. But when I am in debug mode, and enter this in the URL, "myString" is null. Why so? Do I have to change anything else somehwere else?
So if I go to the URL and enter this:
http://localhost:2345/Bank/EmployeeDetails/3d34xyz
public ActionResult EmployeeDetails(string myString) // myString is null
{
return View();
}
In you Global.asax.cs file, you will have the following route mapped by default:
routes.mapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
That means that an url like http://localhost:2345/Bank/EmployeeDetails/3d34xyz will go to the Bank controller, the EmployeeDetails action and pass the value 3d34xyz into a parameter named id. It is perfectly alright to pass a string, but in order to make it work you have two options:
1) Rename the variable to id in your action method.
public ActionResult EmployeeDetails(string id) { ... }
2) Add another route that matches whatever name you want for your string. Make sure to make it more specific than the default route, and to place it before the default route in the Global.asax.cs file.
routes.mapRoute(
"BankEmployeeDetails"
"Bank/EmployeeDetails/{myString}"
new { controller = "Bank", action = "EmployeeDetails", myString = UrlParameter.Optional });
This will pass a default value of null to myString if no value is passed in the url, but with the url you specified you will pass the value 3d34xyz.
Rename myString to id if you are using the default route table.
Assuming you haven't modified the default routes (In your Global.asax.cs):
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
The method is expecting it to be named "id".
Change the name of myString to id.
I had the same problem, you just need to provide the id in the page where you the hyperlink for Details(in the Bank page here)
#Html.ActionLink("Details", "Details", new { id=""})
This solved my problem hope it helps you.
This for MVC 5.
And when you have tryed all of them and still it comes back null then give a full restart for Visual Studio. That's what eventually helped for me.
How to hide controller name in Url?
I use the ASP.NET MVC.
The original url is: http://www.sample.com/Users.mvc/UserDetail/9615
The "Users" is controller name, the "UserDetail" is action name, and the "9615" is UserId.
How can I hide the controller name and action name in the url.
Just like this: http://www.sample.com/9615
I have writed the following code in the Global.ascx.cs to hide the action name:
routes.MapRoute(
"UserDetail", // Route name
"Users.mvc/{UserId}", // URL with parameters
new { controller = "Users", action = "UserDetail", UserId = "" } // Parameter defaults
);
Using the above code I hid the action name and got this url: http://www.sample.com/Users.mvc/9615
But how can I hide the controller name and get this url: http://www.sample.com/9615
Thanks.
The idea is the same. You do just the thing you did to the action. However, your problem arises from the fact that IIS is probably not mapping www.xyz.com/1234 to ASP.NET runtime. To do so in IIS7, enable integrated mode and in IIS6, add a wildcard mapping in handler map that maps everything to ASP.NET.
To add a wildcard map, see http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx (Search for "IIS6 Extension-less URLs" in that page)
After that, simply add a route:
routes.MapRoute("UserDetails", "{UserID}/{*name}",
new { controller = "Users", action = "UserDetail" , UserID=""});
This should do the trick.
MVC recognizes the difference between "{UserID}" and "{id}" so if you are going to have a route with only "{UserID}" in the Url you need to place it first in the list other wise it never gets hit. And make sure the default includes "id" since it will continually loop over "UserDetails" unless the default references id as apposed to UserID. I found this format works for me:
routes.MapRoute("UserDetails",
"{UserID}",
new { controller = "Users", action = "UserDetail", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = "" } // Parameter defaults
);