27
@(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.

2 Answers 2

46

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

Sign up to request clarification or add additional context in comments.

1 Comment

What if there is a parameter/data object?
12
<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" })
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.