Appending Url Fragments to MVC Routes? - asp.net

I want to set up a route in my ASP.NET MVC 3 web application, that has a url fragment appended to it, in the same way as some url's on StackOverflow, e.g:
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732382#1732382
However, I can't see any (clean) way of achieving this at the moment.
Is there an 'out of the box' solution or do I need to build a helper of some description to append a url fragment to the end of a normal route?

You could use helpers. For example:
#Html.ActionLink(
"linkText",
"action",
"controller",
null,
null,
"fragment",
new { id = "123" },
new { #class = "test" }
)
or if you want only an url you could use the GenerateUrl method.

Related

In ASP.NET MVC5, how can I hide the Action name when an a tag is generated in Razor using Url.Action?

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.

Making id'less url in asp.net mvc razor

I am working with URL routing , and have some issues. I want my url to be like this:
www.domain.com/p/myproduct
But I also want to be able to retrieve the ID of the product, without accessing the database. I thought about having a URL like:
www.domain.com/p/myproduct/1
But if I could hide the ID it would be better.
So, how do I do it the simplest way?
Currently my Global.asax has the following route:
routes.MapLocalizedRoute("Product",
"p/{productId}/{SeName}",
new { controller = "Catalog", action = "Product", SeName = UrlParameter.Optional },
new { productId = #"\d+" },
new[] { "Nop.Web.Controllers" });
If all you have is the url then you will have to include the ID there if you want to read it.
The only way to hide it is if you have the ID coming to you from the post of a form say, assuming they have come from a previous page. Then you could store the selected Id and post to url as part of the request.

Route aliasing in ASP.MVC 4

Is it possible to alias routes in ASP.NET MVC4 dynamically?
Basically in WebForms I was using something like this:
foreach (var rule in rules)
{
routes.MapPageRoute("_" + rule.Url, rule.Url, rule.Redirect);
}
and filling the rules from database.
I need to allow the client to rename routes (or make redirects) from the CMS.
Thank you.
Dynamic route aliasing is a difficult process in ASP.NET MVC to be frank. Creating a single route with a dynamic constraint might be a more elegant solution. This needs to set up a constraint that only matches your categories.
routes.MapRoute(
"Product",
"{alias}/{pageNumber}",
new { controller = "Products", action = "Choose", alias = UrlParameter.Optional, pageNumber = 1 },
new { alias = new ProductOptionCondition() } );
The dynamic custom paging in the above is using the dynamic route aliasing option. What have you done exactly. Could you please explain any specific requirement on this, unless its manageable with default route option available with MVC-4.

ASP.Net MVC2 - Registering a Route to Remove "Index"

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.

Creating a URL in the controller .NET MVC

I need to be able to construct a link in the Action on the controller to send an email. What is best practice to do this? I don't want to construct it myself in case my routes change.
Should I have a view for each email and render that and send it? That might be a good way of doing it.
If you just want to get the path to a certain action, use UrlHelper:
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("About", "Home", null);
if you want to create a hyperlink:
string link = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, System.Web.Routing.RouteTable.Routes, "My link", "Root", "About", "Home", null, null);
Intellisense will give you the meaning of each of the parameters.
Update from comments: controller already has a UrlHelper:
string url = this.Url.Action("About", "Home", null);
If you need the full url (for instance to send by email) consider using one of the following built-in methods:
With this you create the route to use to build the url:
Url.RouteUrl("OpinionByCompany", new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}), HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
Here the url is built after the route engine determine the correct one:
Url.Action("Detail","Opinion",new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}),HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
In both methods, the last 2 parameters specifies the protocol and hostname.
Regards.
I had the same issue, and it appears Gidon's answer has one tiny flaw: it generates a relative URL, which cannot be sent by mail.
My solution looks like this:
string link = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("ResetPassword", "Account", new { key = randomString });
This way, a full URL is generated, and it works even if the application is several levels deep on the hosting server, and uses a port other than 80.
EDIT: I found this useful as well.
Another way to create an absolute URL to an action:
var relativeUrl = Url.Action("MyAction"); //..or one of the other .Action() overloads
var currentUrl = Request.Url;
var absoluteUrl = new System.Uri(currentUrl, relativeUrl);
I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:
var urlHelper = new UrlHelper(this.ControllerContext);
Or, you could just use the Controller.Url property if you inherit from Controller.

Resources