c# MVC routing with constants - c#

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")

Related

how can i change-hide controller name from url in asp.net MVC

I'm working on a project using MVC-5. when i run my application, I'm getting this URL: http://192.169.235.120/home/home , but i want it to be like this: http://192.169.235.120/home
so is this possible in MVC-5
You could either change the route as stated in Ahmad's answer or rename your action to Index. MVC automatically routes to http://{host}/ControllerName/ActionName; in your case this seems to be the action "Home" on controller "Home". Rename your action "Home" to "Index" and you'll be able to acces http://{host}/Home, don't forget to rename your view as well.
You should map new route in the Global.asax or RouteConfig.cs if you're using MVC 4, (add it before the default one), for example:
routes.MapRoute("SpecificRoute", "{action}/{id}", new {controller = "MyController", action = "Index", id = UrlParameter.Optional});
// default route
routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional} );
Hope this is helpful :)

ActionLink shows wrong url

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.

Understanding ASP.NET MVC Routes reg

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.

How do I get a pretty URL when creating a link in a Razor View?

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")

MVC 3 How to use MapRoute

Could someone show me how to use the MapRoute method? I have tried creating my own routes, but it's not working. What i want to accomplish is a route that routes "http://servername/home/default.aspx" into controller "Home" and action "Default". Also, would it be possible to say that if the user is browsing the default.aspx "file", it would actually point to the "Index" action?
I have tried reading the MSDN references and googling, but it didn't make me any wiser.
Probably too late to help the developer who raised the question but may help someone else. New to MVC but what I found is the map routes seem to be processed in the order they are added. I had a similar problem, my specific route was not working until I started adding the default route as the last route.
If the default map route is added before your custom one and your custom URL matches the structure defined by the default map route you will never reach your custom route.
The route you want to configure the first part of your question is:
routes.MapRoute(
"",
"home/default.aspx",
new { controller = "Home", action = "Default" }
);
Assuming you wish to 'browse' default.aspx with some sort of parameter you can do something like:
routes.MapRoute(
"",
"home/default.aspx/{param}",
new { controller = "Home", action = "Default", param = UrlParameter.Optional }
);
And you would then need to create your Default action to accept string param.
You also have to make sure the parameter name is the same as the action's parameter name.
Example:
routes.MapRoute(
name: "MyName",
url: "{controller}/{action}/{myParam}",
defaults: new { controller = "MyController", action = "MyAction", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
MyController:
public ActionResult MyAction(string myParam = "")
{
}

Categories