How to pass a parameter in place of controller name in ASP MVC? - asp.net

I would like to know about this.
As we already know, the first parameter to a URL in ASP MVC would be a controller name as in
http://www.somedomain.com/Home/Index
Here, Home is controller and Index is action.
So if some one wanted to pass a value to this URL, he would do so like
http://www.somedomain.com/Home/Index/abc-power-corporation
where abc-power-corporation is a string identifier for a registered organization.
This is pretty much simple and routine. But I would like to know if there is a way to use this URL.
http://www.somedomain.com/abc-power-corporation
so that the URL is much friendlier and easier.
This should take me to the profile of the desired company.

Yes, you can do this in RouteConfig.cs.
Replace this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
With this:
routes.MapRoute(
name: "RetrieveById",
url: "{id}",
defaults: new { controller = "ControllerNametoUse",
action = "ActionNameToUse", id = UrlParameter.Optional }
);
Note that it wouldn't be all that advisable to use both of these at the same time because it would create ambiguity, but it's still possible to use both of them as long as Action is explicitly specified in the URL and you specify the RetrieveById first in RouteConfig.cs.
You could also add more specific routes to get around the ambiguity issue:
routes.MapRoute(
name: "Customers",
url: "Customers/{action}/{id}",
defaults: new { controller = "Customers", action = "Index", id = UrlParameter.Optional }
);
These would need to be specified before the RetrieveById route so that they take precedence.

Related

mvc3 map routes

I am looking to use the following urls and maps some routes accordingly
<domain>/Home/About
<domain>/Home/SiteList
<domain>/Site/<id>/ (this one is defaulted to the details view)
<domain>/Site/<id>/section1/ (this one goes to section1 route in the Site controller)
<domain>/Site/<id>/section2/ (this one goes to section2 route in the Site controller)
e.g.
<domain>/Site/london/siteinfo
The above are covered by
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
However, i also want to use the following routes
<domain>/Site/<siteid>/section1/controller/action (where controller gets data linked to the <siteid> and action is optional)
an example link would be:
<domain>/Site/london/siteinfo/manager (manager is a controller and will list managers for the site)
if have tried various routes and read various posts but could not find anything which was applicable to me.
Can anyone provide some help please?
Thanks
Rudy
Add one more route below "Default":
routes.MapRoute(
"MyRouteName", // Route name
"{controller}/{action}/{id}/{section}/{subsection}", // URL with parameters
new { controller = "Home", action = "Index", id= "", section= "", subsection = "" } // Parameter defaults
);

ASP.NET MVC How can better filter my route?

I have added a new route to my routing table:
routes.MapRoute(
"ModuleRoute", // Route name
"Module/{href}", // URL with parameters
new { controller = "Module", action = "GetHtml" }// Parameter defaults
);
I need this route to match on the following url structure:
/module/123abc.html
The problem is it also matches on this structure
/module/Launch/123abc.html
Calling link :
<%: Html.ActionLink("Launch", "Launch", new { href = item.Href })%>
How do I stop that from happening? I want he second structure to continue to be matched by the default route. I thought that because the number of parameters are different that this would not be a problem.
How can better filter my route to prevent this?
Thanks!
i agree with Max Toro, i've done some testing and that URL doesn't match Module/{href}.
This:
<%: Html.ActionLink("Launch", "Launch", new { href = item.Href })%>
is actually hitting the default route. You see this if you change the default route to the below (note the id is changed to href
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{href}", // URL with parameters
new { controller = "Home", action = "Index", href = UrlParameter.Optional } // Parameter defaults
);
so, this proves it is falling through the first route since it gets a proper url (no querystrings)
what it is doing (when you have the usual default route with id) is that the controller and action are matched but the id isn't. This is OK - the route still matches but leaves off the id. All additional values, such as your href are appended as querystring parameters so you end up with:
module/Launch?href=123abc.html
The way to get around it is to add another route similar to the one above that uses href instead of id
something like:
routes.MapRoute(
"Launch",
"Module/Launch/{href}",
new { controller = "Module", action = "Launch", href = UrlParameter.Optional }
);

ASP.NET MVC : Ignore latter route elements in url for a form's action

I have a URL /products/search where Products is the controller and Search is the action. This url contains a search form whose action attribute is (and should always be) /products/search eg;
<%using( Html.BeginForm( "search", "products", FormMethod.Post))
This works ok until I introduce paging in the search results. For example if I search for "t" I get a paged list. So on page 2 my url looks like this :
/products/search/t/2
It shows page 2 of the result set for the search "t". The problem is that the form action is now also /products/search/t/2. I want the form to always post to /products/search.
My routes are :
routes.MapRoute( "Products search",
"products/search/{query}/{page}",
new { controller = "Products", action = "Search", query = "", page = 1 });
routes.MapRoute( "Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
How can I force Html.BeginForm(), or more specifically Url.Action( "Search", "Products"), to ignore the /query/page in the url?
Thanks
Fixed by adding another route where query and page are not in the url which is kind of counter intuitive because the more specific route is lower down the order
routes.MapRoute(
"",
"products/search",
new { controller = "Products", action = "Search", query = "", page = 1 });
routes.MapRoute(
"",
"products/search/{query}/{page}",
new { controller = "Products", action = "Search"} //, query = "", page = 1 });
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
The order is really important, the first route it hits that matches it uses. Therefore catch all type routes should be at the very end. Here is a helpful route debugger youc an use to figure out what the problem is.
Route Debugger

ASP.NET - ActionResult parameter is coming back null always when passing string - why?

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?

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

Resources