asp.net mvc Html.ActionLink() keeping route value I don't want - asp.net-mvc

I have the following ActionLink in my view
<%= Html.ActionLink("LinkText", "Action", "Controller"); %>
and it creates the following URL http://mywebsite.com/Controller/Action
Say I add an ID at the end like so: http://mywebsite.com/Controller/Action/53 and navigate to the page. On this page I have the markup I specified above. Now when I look at the URL it creates it looks like this:
http://mywebsite.com/Controller/Action/53 (notice the addition of the ID)
But I want it to remove the ID and look like it did originally, like this http://mywebsite.com/Controller/Action (notice no ID here)
Any ideas how I can fix this? I don't want to use hard coded URLs since my controller/actions may change.

The solution is to specify my own route values (the third parameter below)
<%= Html.ActionLink("LinkText", "Action", "Controller",
new { id=string.Empty }, null) %>

It sounds like you need to register a second "Action Only" route and use Html.RouteLink(). First register a route like this in you application start up:
routes.MapRoute("ActionOnly", "{controller}/{action}",
new { controller = "Home", action = "Index" } );
Then instead of ActionLink to create those links use:
Html.RouteLink("About","ActionOnly")

The problem is the built in methods take input from the URL you are currently on as well as what you supply. You could try this:
<%= Html.ActionLink("LinkText", "Action", "Controller", new { id = ""}) %>
That should manually wipe the id parameter.

Don't know why, but it didn't work for me (maybe because of Mvc2 RC). Created urlhelper method =>
public static string
WithoutRouteValues(this UrlHelper helper, ActionResult action,params string[] routeValues)
{
var rv = helper.RequestContext.RouteData.Values;
var ignoredValues = rv.Where(x=>routeValues.Any(z => z == x.Key)).ToList();
foreach (var ignoredValue in ignoredValues)
rv.Remove(ignoredValue.Key);
var res = helper.Action(action);
foreach (var ignoredValue in ignoredValues)
rv.Add(ignoredValue.Key, ignoredValue.Value);
return res;
}

If you either don't know what values need to be explicitly overridden or you just want to avoid the extra list of parameters you can use an extension method like the below.
View
The implementation details are in this blog post

I explicitly set the action name as "Action/". Seems a little like a hack but it's a quick fix.
#Html.ActionLink("Link Name", "Action/", "Controller")

Another way is to use ActionLink(HtmlHelper, String, String, RouteValueDictionary) overload, then there are no need to put null in the last parameter
<%= Html.ActionLink("Details", "Details", "Product", new RouteValueDictionary(new { id=item.ID })) %>

The overloads of Html.ActionLink are changed on the later versions of MVC. On MVC 5 and above. This is how to do this:
#Html.ActionLink("LinkText", "Action", "Controller", new { id = "" }, null)
Note I passed "" for id parameter and null for HTMLATTRIBUTES.

I needed my menu links to be dynamic. Rather than implement a lot of extra code and routing for every single page I simple dispensed with the HTML helper.
#item.MenuItemName

Related

Using Html.BeginForm with querystring

My url looks like this:
customer/login?ReturnUrl=home
In the login view, I have used this pattern of code which works fine.
#using(Html.BeginForm())
{
...
}
This magically generates following html
<form action="customer/login?ReturnUrl=home" method="post">
But now, I need to add an attribute (e.g., data-id="something") in the form. How can I do that? If I don't have any query string, I know I can do something like this:
#using(Html.BeginForm(action, controller, FormMethod.Post,
new { data_id="something" }))
But don't know how to add querystring which should be in html:
<form action="customer/login?ReturnUrl=home" method="post" data-id="something">
I thought about using <form> directly but don't know how to specify querystring which is variable. And I have no idea how to achieve it with Html.BeginForm. Any tip would be appreciated.
RESOLUTION:
For now, I used <form> with following hint How to get current url value in View. The resulting view looks like
<form action="#Request.Url.PathAndQuery" data-id="something" method="POST">
But it would be nice to have an overloaded method of BeginForm for this.
Here's The way that worked for me
Html.BeginForm("Profile", "Partner", routeValues: new {id=Partner.partner_id},method:FormMethod.Post)
It was almost like there was a problem with overloading the method, but by specifying what things are, it seems to work fine...
To create a RouteValueDictionary from the querystring:
RouteValueDictionary queryStringDictionary = new RouteValueDictionary(Request.QueryString.AllKeys.ToDictionary(key => key, key => (object)Request.QueryString[key]));
Then you can use it with Html.BeginForm:
Html.BeginForm(null, null, queryStringDictionary, FormMethod.Post, new Dictionary<string, object> { { "autocomplete", "off" } })
I guess this doesn't directly answer the question, but why not just use a plain old form tag?
<form action='customer/login?ReturnUrl=#Request.QueryString["ReturnUrl"]' method="post" data-id="something">
Alternatively, you can create a custom HtmlHelperExtension that renders a form with path and querystring. In this HtmlHelperExtension you can iterate through your querystring values and populate the routeValueDictionary which you then pass to a Html.BeginForm constructor.
If you don't want something so extensible you can just use the overloaded constructor of Html.BeginForm using
#Html.BeginForm("login", "customer", new {ReturnUrl = #Request.QueryString["ReturnUrl"]},FormMethod.Post, new {data-id="something"});
using Reflector to look at the code,
BeginForm() will pass directly the rawUrl over to the final Form.
Any other overloads on BeginForm will go through a helper utility which will strip the query string.
This works for me :
#using (Html.BeginForm("index", "Photos", routeValues: new { user = pUser, album = pAlbum, }, method: FormMethod.Get))
Explicit route values and method is what is required...
Just incase you wanted to add other attributes as well. use below code
#using (Html.BeginForm("actionName", "controllerName", routeValues: new { lang = "en" }, method:FormMethod.Post, htmlAttributes: new { #class= "my-form", enctype = "multipart/form-data" }))
Try #using(Html.BeginForm(null, null, FormMethod.Post, new { data_id="something" }))
It should use the default logic to construct the url, just as if you used BeginForm()
(never tried that though in such case, but I believe it should work)

MVC3 routing issue with nullable parameter

I have an odd issue. I have a controller action which takes a couple of optional parameters
Function Index(sectionID As Integer?, title As String) As ActionResult
Return View()
End Function
I then have added a specific route for this action method so that we get pretty urls for this page
routes.MapRoute( _
"By_Section", _
"home/{sectionID}/{title}", _
New With {.controller = "Home", .action = "Index", .sectionID = Nothing},
New With {.sectionID = "\d+"}
)
This all works. However, when I am on a page where the sectionID is set (for example http://localhost/home/index/1/test), the following piece of code produces an odd output.
<%= Url.Action("Index", "Home")%>
Instead of showing http://localhost/home/index as you might expect, it shows http://localhost/home/index/1/test. So it appears it is picking up the sectionID and title from the current url and automatically inserting them into the Url.
How can I prevent this from happening?
Thanks
James
Yes, this is expected behaviour, the routing system will reuse parameter values from the current request if you haven't provided a new value explicitly. The best option when rendering links is to specify explicit values for all of your routing parameters.
<%= Url.Action("Index", "Home", new { sectionID = (int?)null }) %>

How to pass query string parameter in ActionLink in MVC

I am having following action link:
<%= Html.ActionLink("Check this", "Edit", "test",
new { id = id }, new { style = "display:block" })%>
How do I include data=name as query string. Some thing like this:
link?data=name
4th parameter of Html.ActionLink can have any number of properties:
<%= Html.ActionLink("Check this", "Edit", "test",
new { id = id, data=name }, new { style = "display:block" })%>
These properties are inserted into URL based on routing, but if the property name cannot be matched into any route it is added as URL GET parameter.
So if you have standard route {controller}/{action}/{id}, you will get the URL:
test/Edit/[id]?data=[name]
from the above code.
Pass Query String By this way
#Html.ActionLink("Delete Record", "Home", "Delete", new { id=Id},null)
By above code you will get the url like(Suppose Id=1): /Home/Delete/1
and if you want to add more parameters to query string then:
#Html.ActionLink("Delete Record", "Home", "Delete", new { id=Id, Name=name},null)
By above code you will get the url like(Suppose Id=1 and Name=India) :
/Home/Delete/1?Name=India
I got tired of banging my head against a wall with the html.actionlink. Works great when you just want to route it against straightforward routing calls, but absolutely refuses to cooperate when you want to add a simple querystring at the end.
I don't an ID at then end, I want to be able to add some kind of actual Querystring with the "?".
So anywhere I needed a Querystring I switched to using the url.action inside the anchor tag.
<a href='#url.action("Action","route")?Parameter=Value' >Text for Link Name</a>
At least it works and I can stop getting headaches over something that should have been a very simple task. Someone needs to get their heads out of their butts and make the ActionLink work properly for Querystrings in the MVC routing.
I know this is kind of old question but.
In case the below code doesn't generate the <a href="/?param=value" />.
<%= Html.ActionLink("Text", "Action", "Controller", new { param=value }, null)%>
I would advice checking whether you action has at least one [Route] attribute (I used [Route("/")] for example).
Hope it helps.

Adding rel and title to ASP.NET MVC Action Links

I decided primarily for SEO reasons to add the "rel" to my action link, but am not sure that the way I have gone about this is going to follow "best practices." I simply created a new Extension method as shown below.
Is this the best way to go about doing this? Are there things that should be modified in this approach?
VIEW
<%= Html.ActionLink("Home", "Index", "Home")
.AddRel("me")
.AddTitle("Russell Solberg")
%>
EXTENSION METHODS
public static string AddRel(this string link, string rel)
{
var tempLink = link.Insert(link.IndexOf(">"), String.Format(" rel='{0}'", rel));
return tempLink;
}
public static string AddTitle(this string link, string title)
{
var tempLink = link.Insert(link.IndexOf(">"), String.Format(" title='{0}'", title));
return tempLink;
}
You can add any extra html parameter very easily and don't need to write your own extension methods
<%= Html.ActionLink("Home", "Index", "Home", null,
new { title="Russell Solberg", rel="me"}) %>
You can add attributes to the action link with anonymous class passed as fourth parameter:
<%= Html.ActionLink("Home", "Index", null,new{ #title="Russell Solberg", #rel="me" }) %>
The # sign is used to allow you to specify attribute names that are c# reserved keywordk (like class).
I would probably not do it that way as that will make this possible for any string. You can already do this with the action link without creating your own extensions methods. Like this:
<%=Html.ActionLink("Home", "Index", "Home", null, new {title = "Russell Solberg", rel = "me"}) %>
Personally I prefer to use Url.Action() and write the <a /> tag myself as I think thats more readable.

Asp.Net MVC Call another controller from view

Let say I'm on the page "Home/Index" and I want to go to the page MyOtherController/Index/1
How can I do this ?
I try :
<%= Html.ActionLink("Test", "Index", "MyOtherController", new { id=item.Id }) %>
Did I also have to add a route in Global.aspx file ?
One option is to specify the name of the controller in the list of routevalues:
<%= Html.ActionLink("Test", "Index"
, new { controller = "MyOtherController", id = item.Id }) %>
An alternative is to use the overload of ActionLink with htmlAttributes = null:
<%= Html.ActionLink("Test", "Index"
, "MyOtherController", new { id = item.Id }, null) %>
The default route in the ASP.NET MVC template takes care of the routing in this case.
I don't believe ActionLink has an overload matching that particular signature. You would need to add "null" after your route values to find a matching one (for htmlAttributes). Ole's solution would be cleaner though so it's really a matter of preference. It also will help with readability so you don't have to guess whether each parameter is link text, an action/controller, etc.

Resources