How to pass query string parameter in ActionLink in MVC - asp.net-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.

Related

Get id from clicked url

It is necessary for me at a choice the user of a subject of a forum on the page from a database contents of the chosen subject were loaded on the page. I will describe how I approached to the solution of this task. This code presents forum threads:
<a href='Home/ThreadView' id='1'>About all</a>
<a href='Home/ThreadView' id='2'>Cars</a>
ThreadView action has code:
[HttpGet]
public ViewResult ThreadView(int id)
{
ViewData[ThreadViewSelector] = Thread.GetThreadView(id);//Thread is a model.
return View();
}
When I click on any link an error occurs:
Parameters dictionary contains record with value NULL for parameter "id" of type "System.Int32"
How to solve this problem ?
The ID attribute in your link is the id of the HTML element... so, that id could be useful if you want to do something with javascript.
With your current code, the id is never sent to the controller action, that is why the error you are seeing. You need to put the ID in the href attribute along with the Controller/Action.
You have 2 options to pass the id to your controller action:
If you have the out-of-the-box routing rules you can use:
<a href='Home/ThreadView/1' id='1'>About all</a>
You can send it via query string this way:
<a href='Home/ThreadView/?id=1' id='1'>About all</a>
EDIT:
The element id is not required in order to have the routing working.
Instead of doing this manually, you could use one of the Razor Helpers:
#Html.ActionLink("About all", "Home", "ThreadView", new { id = 1})
If you need to add some attributes to the link element, besides the routing parameters:
#Html.ActionLink("About all", "Home", "ThreadView", new { id = 1}, new { #class = "redLink", id="aboutall"})

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 }) %>

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.

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

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

Resources