Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 Razor: How to get Action URL in a Javascript string variable?

@(Html.ActionLink("Link Label",      "ActionMethodName",      "ControllerName",      null, // parameter object, then html object     null)) 

produces

<a href="/ControllerName/ActionMethodName/">Link Label</a> 

If I want to reference the /ControllerName/ActionMethodName/id in a JavaScript template for the Edit or New link, how would I assign that to a JavaScript variable?

attempt:

<script type="text/javascript">     var actionUrl = '@(Html.ActionLink("","ActionMethodName",                                        "ControllerName",null,null))'; </script> 

but at that point, I would have to use Javascript to remove the unwanted <a href... characters in the string.

like image 222
Zachary Scott Avatar asked May 23 '11 04:05

Zachary Scott


2 Answers

@Url.Action("ActionMethodName", "ControllerName") will generate a path.

like image 92
Justin Soliz Avatar answered Oct 22 '22 12:10

Justin Soliz


<script type="text/javascript">     var actionUrl = @Html.Raw(Json.Encode(Url.Action("ActionMethodName", "ControllerName"))); </script> 

or if you already have this actionLink somewhere inside the page you could use it directly:

var actionUrl = $('#mylink').attr('href'); 

Just ensure to provide a unique id in order to simplify the selection:

@(Html.ActionLink(     "Link Label",      "ActionMethodName",      "ControllerName",      null,     new { id = "mylink" }) ) 
like image 33
Darin Dimitrov Avatar answered Oct 22 '22 13:10

Darin Dimitrov