Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write action links using javascript in ASP.NET MVC?

I have a script that appends some rows to a table. One of the rows has a delete link, and for that I am using a ActionLink, however the id of the element is received via js, and this is nor working:

 $("#Table").last().append('<tr><td><a href=\"<%:Html.ActionLink("Delete", "DeleteElementFromSet", new {id=%>Id<%})%>">Delete</a></td><td>'+Id+'</td></tr>');

where Id is a javascript variable that gets its value from the value of a dropdownlist.

Is there a way to use ActionLink like this? or do I have to write down the path manually?

like image 845
Francisco Noriega Avatar asked Jul 24 '26 07:07

Francisco Noriega


2 Answers

Because the id is known only at the client side you will need to construct the proper url. This being said never mix C# and javascript. Here's how you might proceed:

Start by declaring a global variable that will hold the delete link without the id part:

<script type="text/javascript">
    var deleteUrl = '<%: Url.Action("DeleteElementFromSet") %>';
</script>

and then in a separate javascript file:

$('#Table').last().append(
    $(document.createElement('tr'))
        .append($(document.createElement('td'))
            .append($(document.createElement('a'))
                .attr('href', deleteUrl + '/' + Id)
                .text('Delete')
            )
        )
        .append($(document.createElement('td'))
            .text(Id)
        )
);

Notice that you should use Url.Action instead of Html.ActionLink because you already have the anchor manually generated.

Remark: avoid using GET verbs for deleting. You might have bad surprises. Use proper verb (or at least POST) when modifying state on the server such as deleting.

like image 193
Darin Dimitrov Avatar answered Jul 26 '26 05:07

Darin Dimitrov


Just like you have an action link helper in MVC. Create a helper in JavaScript where you provide an action, controller, and id to create a link.

like image 41
John Hartsock Avatar answered Jul 26 '26 07:07

John Hartsock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!