Working on Html.ActionLink

ASP.NET C#, Web Development Add comments

Few weeks ago, I’ve been studying Microsoft Visual Studio Web 2012 in my free time and focusing on Visual C# .Net since I have a background on desktop/window application development using Visual C#. I posted this just to remind the things that I took time to figure it out. I’ve been banging my head getting the good answers. Though there’s the MSDN but there’s no samples and I find it horrible documentation.

So, I’m working on ASP.NET MVC 3 Web Application and wondering how I could create the Request URI using Html.ActionLink(). It took me almost an hour to figure it out. Thanks to Gavin Coates for pointing it out what made my codes wrong.

The URI I want to have is;

http://localhost:xxxx/controller/action?task=view&xid=7

The syntax will be (according to http://msdn.microsoft.com/en-us/library/dd492124(v=vs.108).aspx);

public static MvcHtmlString ActionLink(
	this HtmlHelper htmlHelper,
	string linkText,
	string actionName,
	string controllerName,
	Object routeValues,
	Object htmlAttributes
)

And the right codes are;

@Html.ActionLink("Text Here", "ActionName", "ControllerName", new { task = "view", xid = 5 }, null)

That’s it.. It works fine with my app. Wehehe!

What when wrong before I solved was I didn’t put null at the last arguments. If you don’t put null, your object will become a RouteValueDictionary (I think and not sure about this terms yet) which it should be routeValues.

See http://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions(v=vs.108).aspx for more information about this.

Somehow, the link creation above was crossing to another Controller. What if creating a link within a current controller? The answer will be;

@Html.ActionLink("Text Here", "ActionName", new { task = "view", xid = 5 })

As you can see, I didn’t specify the Controller name because you are currently on the controller/page.

Hope this helps too to the newbies… 🙂

  • Suresh kumar

    Thanks for your grateful informations, am working in FNT software solutions, so it will be helpful info for my works.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in