Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get just href part of Html.ActionLink result text

Tags:

asp.net-mvc

As you know,

<%=Html.ActionLink("Back to List", "Index") %>

generates html like this : <a href="/Content/Index">Back To List</a>

But I need just href part.

I will use it in JS code and I do not want to write manually.

Can I gerenate what I need part ?

like image 403
Selçuk Yavuz Avatar asked Jan 20 '10 22:01

Selçuk Yavuz


People also ask

What is difference between HTML ActionLink and URL action?

There is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.

What is HTML ActionLink ()?

ActionLink(HtmlHelper, String, String, String, String, String, String, Object, Object) Returns an anchor element (a element) for the specified link text, action, controller, protocol, host name, URL fragment, route values, and HTML attributes.

How can we call post method using ActionLink in MVC?

ActionLink is rendered as an HTML Anchor Tag (HyperLink) and hence it produces a GET request to the Controller's Action method which cannot be used to submit (post) Form in ASP.Net MVC 5 Razor. Hence in order to submit (post) Form using @Html. ActionLink, a jQuery Click event handler is assigned and when the @Html.


2 Answers

Try this

<%=Url.Action("Action","Controller")%>
like image 157
Mathias F Avatar answered Sep 22 '22 21:09

Mathias F


Mathias's answer is what I use. ASP.NET MVC 2 gives you strongly types Url.Action too.

I find this most useful in javascript so:

<script type="text/javascript">
   var urlToPostTo = '<%= Url.Action<HomeController>(h => h.ContactUs()) %>';
   var someData = 'Some valuable data!';
   $.post(urlToPostTo, someData, function()
   {
      alert('Successfully posted some data to some url');
   });
</script>

This allows you to avoid putting hardcoded paths in your markup, leaving you with a slightly more maintainable solution.

That said, I'm still hoping that these will be compile time checked as normal when MVC 2 is finally released.

like image 44
Tristan Warner-Smith Avatar answered Sep 25 '22 21:09

Tristan Warner-Smith