I have some pre-defined URLs in routing table actually directing to same controller and action, but different language. For example
routes.MapRoute(
"Contact", // Route name
"contact", // URL with parameters
new { controller = "Home", action = "Contact", lang="en" } // Parameter defaults
);
routes.MapRoute(
"Contact2", // Route name
"iletisim", // URL with parameters
new { controller = "Home", action = "Contact", lang="tr" } // Parameter defaults
);
When i use Html.ActionLink in View and run application, URL shows the first route, for example:
#Html.ActionLink(Resources.Contact, "Contact", "Home")
When current language is tr when page rendered URL is : /contact which should be /iletisim instead.
When i change the order of route mappings then en language pages shows wrong URL.
How can I solve this problem?
When matching a route from ActionLink, you must take all of the parameters that the route generates into consideration. The framework will always return the first match for the supplied route values.
In your case, you are supplying the route values:
controller = "Home"
action = "Contact"
Which given the lack of other information will match your Contact route (the first route with controller = "Home", action = "Contact").
If you want to match a specific route, then you need to pass the lang route value as well.
#Html.ActionLink(Resources.Contact, "Contact", "Home", new { lang = "tr" }, null)
That will match the Contact2 route.
Alternatively, you can put the lang into the URL of the page, which would ensure that it is part of the current request as shown in ASP.NET MVC 5 culture in route and url
. Then MVC will automatically supply this value to all of your ActionLinks and other UrlHelper based methods.
Related
I have a .NET MVC site with multiple tenants all with their own sub-domains. And I'm trying to mask the controller location for a certain subset of those tenants as they're segmented to an area of the site.
For example I want subdomain.domain.com to point to /Controller/View without the extra stuff on the end of the domain.
More specifically,
http://subdomain.domain.com/Controller/View
Becomes:
http://subdomain.domain.com
What's the best way to accomplish this? In the Web.config?
you can use this in global.asax to remove controller and view part from url.
routes.MapRoute("SpecificRoute", "/{id}", new {controller = "YourController", action = "YourAction", id = UrlParameter.Optional});
// default route
routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional} );
Also you can use Route() over your action
[Route("")]
public ActionResult YourAction()
{
...
}
Url will be like http://example.com/
I've created a system in MVC using the NerdDinner tutorial as a base to work off.
Everything was working fine until I used single action methods such as
Here is the global.asax.cs
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "mysample", id=UrlParameter.Optional }
);
which routes to
http:localhost/Home/mysample
i just want to create routes which has more than one action in the sense
http:localhost/<controller>/<action>/<params>
ex: localhost/mycontroller/myaction/details/myname
Any help much appreciated.
Thanks.
update 1:
i have writen router like this as
routes.MapRoute(
"myname", // Route name
"{controller}/{action}/{details}/{myname}", // URL with parameters
new { controller = "mycontroller", action = "myaction", details= "details", myname= "" } // Parameter defaults
);
and retried the value with following syntax as
String name=RouteData.Values["myname"].ToString();
it works fine .
but even though the url called as
localhost/mycontroller/myaction/details
its being routed to that controller and error is being thrown as null reference...
how to avoid it?
You can't define multiple actions in one MVC route.
In MVC routing configuration is used for mapping your Controlers and Actions to user friendly routes and:
Keep URLs clean
Keep URLs discoverable by end-users
Avoid Database IDs in URL
Understanding default route config:
routes.MapRoute(
name: "Default", // Route name
routeTemplate: "{controller}/{action}/{id}", // URL with parameters
defaults: new { controller = "Home", action = "mysample", id=UrlParameter.Optional }
);
The "routeTemplate" property on the Route class defines the Url
matching rule that should be used to evaluate if a route rule applies
to a particular incoming request.
The "defaults" property on the Route class defines a dictionary of
default values to use in the event that the incoming URL doesn't
include one of the parameter values specified.
Default route will map all requests, because it has defined default values for every property in routeTemplate, {} means that property is variable, if you not provide value for that param in URL, it will try to take default value if you provide it. In default route it has defined defaults for controller, action and id param is optional. That means if you have route like this:
.../Account/Login
It will take you to Account controller, Login action and because you didn't specified prop and it is defined as optional it will work.
.../Home
This will also work, and it will take you to Home contoller and mysample action
When you define custom route, like you did:
routes.MapRoute(
"myname", // Route name
"{controller}/{action}/{details}/{myname}", // URL with parameters
new { controller = "mycontroller", action = "myaction", details= "details", myname= "" } // Parameter defaults
);
You didn't specified myname as optional and you didn't specified it your route, that means that your URL: localhost/mycontroller/myaction/details wan't be handled by your custom route myname. It will be handled by default route. And when you try to access your myname param in controller it wan't be there and you will get null reference error. If you want to specifie default value of your parameter if not present in url you need to do that in your controller. For example:
public class MyController : Controller
{
public ActionResult MyAction(string details = "details", string myname = "")
{
...
and change your custom route to:
routes.MapRoute(
"myname", // Route name
"{controller}/{action}/{details}/{myname}", // URL with parameters
new { controller = "mycontroller", action = "myaction", details= UrlParameter.Optional, myname= UrlParameter.Optional } // Parameter defaults
);
But you can define only one controller and only one action, rest of the routeTemplate are parameters.
You can't define two action in one route. It make no sense.
I'm asking how to do a link with #Url.Action in a Razor view to make a link like
Controller/Action/123
I already made #Url.Action("Action","Controller", new { #ViewBag.ID }) but it makes me a link like
Controller/Action?ID=123
How do I make a URL without the querystring in the razor view?
Try:
#Url.Action("actionname", "controllername", new { id = ViewBag.Id})
I think the problem is just that you haven't specified that the value in your route parameters collection is the "id". Of course, I'm assuming that you're using the default route configuration in RegisterRoutes.
Tip: you can also use Html.ActionLink() which saves you the trouble of creating an <a> tag yourself:
#Html.ActionLink("linkText", "actionName", "controllerName", new { id = ViewBag.ID }, null);
This will generate an <a> tag with the linkText and the same url as Url.Action() which you can see in Jeff's answer.
Note: don't forget to add null as the last parameter, otherwise it will use the wrong overload and use the anonymous type as htmlAttributes.
Use Url.RouteUrl(String, Object) and notUrl.Action()
Use the default route name.. which must be Default
so your code should be :
#Url.RouteUrl("Default", new {controller = "SomeControler", action = "SomeAction" , id = #ViewBag.ID })
Doing that will give you url as follows : SomeController/SomeAction/5 (assuming ID was 5)
This happens because of the by default the project mvc template contains a Default route as follows :
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
You can create more fancy urls if you wish or if you need more parameters, by adding more routes into routing table
here's the description : http://msdn.microsoft.com/en-us/library/dd505215(v=vs.108).aspx
#Url.Action("Action/" + #ViewBag.ID,"Controller")
I am working in Asp.net mvc3 application.I have created url for product detail page like this
routes.MapRoute(
"ProductDetail",
"{category}/{title}-{id}",
new { controller = "ProductDetail", action = "Index" }
);
for other controller using this
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Following code creating this url
www.example.com/Shoes/blackshoes-100
Now Problem is that i want to use this url for ProductDetail page if add any other controller and action name it will redirect to ProductDetail page like this
www.example.com/Home/Index-100
How can i restrict this url for ProductDetail Page?
is this right way to do this?
I wan to hide Controller and Action of Productdetail page.
Category,title and id values are changing for every product.
You have to define routes for any other page you have and map those routes before you map your peoduct detail route. Then the route maching mechanism will find them first and use them.
Of course you do not have to map route for every single action. You can create some prefixes for example for diffrent controllers like example below, to catch all routes for Home controller actions:
routes.MapRoute(
"Home",
"Home/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
I'm trying to generate an actionlink on a page that has the following route:
/{controller}/{type}/{sub}
The link needs to go to:
/{controller}/{type}/{sub}/new
How do I specify the "/new" portion of the url in an object or RouteValueDictionary so that I can pass it to the HTML.ActionLink?
StackOverflow won't let me answer my question for another 8hrs... so:
Thanks Justin.
Your suggestion worked, but for the sake of completeness, I discovered the method using the Html.ActionLink method:
You just need to specify the ActionName of the method that resolves that route. The framework appears to automatically work out that you want it on the same path as the current page.
So, if your route is:
routes.MapRoute(
"New", // Route name
"{controller}/{type}/{sub}"/new, // URL with parameters
new {controller = "DefaultController", action = "Create", id = UrlParameter.Optional});
The link is:
Html.ActionLink("Create New Page", "Create")
Approving Justin's method as it worked for me
As far as I know, the default implementations of ActionLink do not support this, so you have the following options:
Build it manually in this case (I am not in front of Visual Studio, so the syntax might be off a little)
<a href="#Url.Action(
"Controller", "Method", new { type = "type", sub = "sub" }));/new">
link text</a>
Or, you could create a new helper method to encapsulate something like this, if it happens often enough.
routes.MapRoute(
"New", // Route name
"{controller}/{type}/{sub}"/{new}, // URL with parameters
new {controller = "DefaultController", action = "Index", id = UrlParameter.Optional});
routes.MapRoute(
"Default", // Route name
"{controller}/{type}/{sub}", // URL with parameters
new {controller = "DefaultController", action = "Index"});
should be something like that
I would create the route as AD.Net suggests above and then use the Html.RouteLink extension helper to create the link, this way, if you ever decide to change the url/link it's automatically picked up by the routing engine
routes.MapRoute(
"New", // Route name
"{controller}/{type}/{sub}"/{new}, // URL with parameters
new {controller = "DefaultController", action = "Index", id = UrlParameter.Optional});
Html.RouteLink("Create New Page", "New")