How to create a dynamic @Html.ActionLink with JQuery?

0

I'm trying to create a dynamic @Html.ActionLink fault with JQuery but I'm not getting it, how do I do that?

$('#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>');
        });
    }
    
asked by anonymous 05.11.2016 / 12:31

1 answer

1

Instructions that begin 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 @ will not be processed by the server and JavaScript also does not know how to interpret this.

A possible solution is to put a script in your View 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, the HTTP address will be printed, only needing to transform into a link using the a tag.

    
05.11.2016 / 13:24