Scott Peterson
Scott Peterson

Reputation: 73

Create MVC action link in javascript

New to MVC/jquery, having problems creating a link dynamically.

If the user types into a text box and hits an add button, we invoke the following javascript:

    addItem: function (button) {
        var text = this.$text.val();
        var $newCell = $('<td>');
        $newCell.text(text);
        var $hidden = $('<input type="hidden" />');
        $hidden.attr('name', this.name);
        $hidden.val(text);
        $newCell.append($hidden);
        $newCell.append('</td>');
        var $newLinkCell = $('<td>');
        var $newLink = $('<a href="#" id="newLink">EPA Action Link</a>');
        var $newLinkTarget = '<%: @Html.ActionLink("EPA Action Link", "EPARedirect", new { EPAId = "' + text + '" }, new { target = "_blank" }) %>';
        $newLink.attr("href", $newLinkTarget);
        $newLinkCell.append($newLinkTarget);
        $newLinkCell.append('</td>');
        var $html = $('<tr>');
        $html.append($newCell);
        $html.append($newLinkCell);
        $html.append('</tr>');
        this.$table.append($html);

        this.initItem($newCell);
        this.$text.val('');
    }

So what I'm doing is locating a table, and adding a new row with two cells: the left to show the data and the right to show a link with that data as a parameter.

For existing items, I have the same ActionLink in the cshtml file (except the EPAId is built through a jquery variable of "@item").

Anyway, I've been trying to figure out how to dynamically build the same type of link in my add function. All I'm getting is the literal text of $newLinkTarget. I guess this makes sense, it's not being shoved through server's jquery rendering.

Am I on a completely wrong path here?

Upvotes: 0

Views: 1505

Answers (1)

Shane Courtrille
Shane Courtrille

Reputation: 14097

You can't generate a link client side since you need to take into account routing which isn't available client side. You will either need to generate a base Url using @Url.ActionLink which you store in a JS variable and then use as a base on the client OR have a Ajax method you can call that can generate the path for you.

Upvotes: 1

Related Questions