0

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?

1 Answer 1

1

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.

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

1 Comment

or the text box he is typing on could have extra data-* attribute like data-url and its value is the url that is generated server side

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.