Anyone know how I can turn the URL from:
www.contoso.com/locations?Country=Vietnam
into
www.contoso.com/Vietnam
in Razor, C#, Webforms. (I'm using Webmatrix)
ie - to create FriendlyURLS from search results.
thanks
In RouteConfig.cs, add the following route:
routes.MapRoute(
"Vietnam",
"{vietnam}",
new { controller = "NameOfYourController", action = "NameOfYourAction" },
new { vietnam = UrlParameter.Optional }
);
You have to specify the name of the controller (without the word controller) and the action which will process the request.
Related
I am trying to prepare a 301 redirect for a typo I made 'recieved'
I am struggling to find a way of getting the url from the action and controller names.
I am aware of UrlHelper.Action but it does not exist within Global.asax. How do I gain access to this method?:
// Add permanent redirection for retired pages (Application_BeginRequest())
if (HttpContext.Current.Request.Url.LocalPath.ToLower().StartsWith("/blah/listrecieved"))
{
HttpContext.Current.Response.RedirectPermanent(/*Need url generated from action and controller*/);
}
Alternatively I have created a route, if that's how I should be getting the string, this is also fine but I am unsure of how:
routes.MapRoute(
name: "blah-list-received",
url: "blah/list-received",
defaults: new { controller = "Blah", action = "ListReceived" }
);
for example, it might look like this:
// Add permanent redirection for retired pages
if (HttpContext.Current.Request.Url.LocalPath.ToLower().StartsWith("/blah/listrecieved"))
{
HttpContext.Current.Response.RedirectPermanent(routes.GetUrl( "blah-list-received" ) );
}
You need to construct the UrlHelper yourself:
var url = new UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes)
.Action("YourAction",
"YourController",
new { paramName = paramValue });
See MSDN
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 ASP.Net MVC2 application.
In that i have used URL Routing
To get URL as
https://localhost/StudentDetail/SortField
I have written below code in Global.asax
routes.MapRoute(
"StudentDetail", // Route name
"StudentDetail/{SortField}", // URL with parameters
new { controller = "UDashboard", action = "UAboutMeStudentDetails",
SortField = "Major" }
);
And In my view link is as below
<a href="/StudentDetail?SortField='Major'" >Students</a>
But it is not working. and my URL is
https://localhost/StudentDetail?SortField='Major'
Can anyone please help me to get the required URL..?
I want URL as
https://localhost/StudentDetail/SortField
Thanks In Advance, Prashant
I think you have an incorrect thought on how routing works. Your route:
routes.MapRoute(
"StudentDetail", // Route name
"StudentDetail/{SortField}", // URL with parameters
new { controller = "UDashboard", action = "UAboutMeStudentDetails",
SortField = "Major" }
);
Will take the SortFeild parameter (Major, Gpa, etc), and replace {SortField} with that value. So, using the following actionlink:
#Html.ActionLink("Student Details", "UAboutMeStudentDetails", new {controller="UDashboard", SortField = "Major})
would produce the following HTML
Student Details
Note that the value of SortField has replaced the {SortField} parameter in your route. You would never get a URL looking like what you are requesting as how would you get the value of SortField to the action?
In ASP.net MVC I am using Url.RouteUrl & Html.RouteLink to create some links in my page.
Considering the following default route:
routes.MapRoute(
null,
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Using Url.RouteUrl(new { controller = "Products", action = "List", sort = "newest" }) will produce the URL /Products/List?sort=newest.
So far this is exactly what I want. What I'm not sure how to accomplish is the following. If I am currently on /Products/List?sort=newest. and I need to provide the user with a URL to change the number of products listed per page:
`/Products/List?sort=newest&pagesize=30`
How can I use Url.RouteUrl to generate the following URL so that:
If I am currently on a page that has sort=newest, it retains this value: /Products/List?sort=newest&pagesize=30
If I am currently on a page that doesn't have sort, it omits it: /Products/List?pagesize=30
For an example of what I mean, you can look at stackoverflow. If I look at questions and change to view featured questions, and then click on the page size at the bottom it will retain the sorting but then append the page size to the URL.
Url.RouteUrl(
new {
controller = "Products",
action = "List",
sort = Request["sort"],
pagesize = "30"
}
)
If this is invoked from /Products/List it will produce /Products/List?pagesize=30. And if it is invoked from /Products/List?sort=newest it will produce /Products/List?sort=newest&pagesize=30.
Currently, I have URLs that look like this:
http://www.example.com/user/create
http://www.example.com/user/edit/1
But now, I have to support multiple organizations and their users. I need to have something like this:
http://www.example.com/org-name/user/create
http://www.example.com/org-name/user/edit/1
I was having trouble getting the routes to work just perfectly, so I had to add a token to the beginning of the organization name so that routing wouldn't confuse it with a controller/action pair. Not a huge deal but my URLs look like this now:
http://www.example.com/o/org-name/user/create
http://www.example.com/o/org-name/user/edit/1
That's fine. I can live with that.
Here's where I'm running into trouble:
When I generate URLs once I have an organization selected, it's not persisting the organization name. So when I'm here:
http://www.example.com/o/org-name
...and I use Url.Action("User", "Create") to generate a URL, it outputs:
/user/create
...rather than what I want:
/o/org-name/user/create
This is what my routes look like (in order):
routes.MapRouteLowercase(
"DefaultOrganization",
"{token}/{organization}/{controller}/{action}/{id}",
new { id = UrlParameter.Optional },
new { token = "o" }
);
routes.MapRouteLowercase(
"OrganizationDashboard",
"{token}/{organization}/{controller}",
new { controller = "Organization", action = "Dashboard" },
new { token = "o" }
);
routes.MapRouteLowercase(
"DefaultSansOrganization",
"{controller}/{action}/{id}",
new { controller = "Core", action="Dashboard", id = UrlParameter.Optional }
);
It's similar to this question ASP.NET MVC Custom Routing Long Custom Route not Clicking in my Head.
I have a feeling this is going to end up being obvious but it's Friday and it's not happening right now.
EDIT:
Womp's suggested worked but would this be the best way to automate this?
public static string ActionPrepend(this UrlHelper helper, string actionName, string controllerName)
{
string currentUrl = helper.RequestContext.RouteData.Values["url"] as string;
string actionUrl = string.Empty;
if (currentUrl != null)
{
Uri url = new Uri(currentUrl);
if (url.Segments.Length > 2 && url.Segments[1] == "o/")
actionUrl = string.Format("{0}{1}{2}{3}", url.Segments[0], url.Segments[1], url.Segments[2],
helper.Action(actionName, controllerName));
}
if(string.IsNullOrEmpty(actionUrl))
actionUrl = helper.Action(actionName, controllerName);
return actionUrl;
}
EDIT:
Fixed my routes to work rather than hacking it together. The final solution didn't need the stupid {token} in the URL. Maybe this'll help someone else:
routes.MapRouteLowercase(
"Organization",
"{organization}/{controller}/{action}/{id}",
new { controller = "Organization", action = "Dashboard", id = UrlParameter.Optional },
new { organization = #"^(?!User|Account|Report).*$" }
);
routes.MapRouteLowercase(
"Default",
"{controller}/{action}/{id}",
new { controller = "Core", action = "Dashboard", id = UrlParameter.Optional }
);
Url.Action uses route values to generate the actual URL's by querying the virtual path provider and attempting to match the most specific route. In the form that you are using, you are supplying values for the controller and the action, which is as deep as most simple websites go, hence the convenient form of the method. When Url.Action queries the routing system, it only has a "controller" and an "action" segment to match.
If you give the method the rest of the routing information it needs, it will properly match the route that you desire, and will return the correct URL. Try this:
Url.Action("User", "Create", new { token = "o", organization = "organization" })