How to create a dynamic @Html.Actionlink with Jquery?

Asked

Viewed 296 times

0

I’m trying to create a @Html.ActionLink dynamic with Jquery but I’m not getting, how to do it ?

$('#tableView > tbody').empty();   
    if (data["CategoriaProduto"].length > 0) {
        $.each(data["CategoriaProduto"], function (i, cp) {
            var editLink = $('@Html.ActionLink("Edit", "edit", "CategoriaProduto"), new {id = ' + cp.id + '}');           

            $('#tableView > tbody:last-child').append('<tr>'
                                                    + '<td class="text-capitalize small">' + cp.descricao + '</td>'
                                                    + '<td class="col-md-1">' + editLink + '</td>'
                                                    + '</tr>');
        });
    }
  • This code is inside a JS file or is in the view?

  • @goenning inside a JS file, I can fill the table with cp.descricao, but I’m unable to create the @Html.ActionLink

1 answer

1


Instructions starting with @ are processed on the server side. Your file being a Javascript, will be sent to the client without any pre-processing. This means that the @ will not be processed by the server and Javascript also does not know how to interpret this.

A possible solution is within your View put a script like this:

<script type="text/javascript">
    var editUrl = '@Url.Action("Edit", "CategoriaProduto")' + '/';
</script>

This will create a global scope variable within Javascript. This variable can then be accessed by your file. It would look like this:

$('#tableView > tbody').empty();   
    if (data["CategoriaProduto"].length > 0) {
        $.each(data["CategoriaProduto"], function (i, cp) {
            var fullUrl = editUrl + cp.id;         

            $('#tableView > tbody:last-child').append('<tr>'
                                                    + '<td class="text-capitalize small">' + cp.descricao + '</td>'
                                                    + '<td class="col-md-1">' + fullUrl + '</td>'
                                                    + '</tr>');
        });
    }

In this example will be printed the HTTP address, missing only turn into a link using the tag a.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.