Dieter
Dieter

Reputation: 331

Building HTML and appending using jQuery

I'm stuck with a scenario such as the following:

$(document).ready(function () {
        var param1 = "A";
        var param2 = "B";
        var param3 = "C";
        $("ul#SomeUL").append('<li><%: Ajax.ActionLink("Click Me", "SomeAction",  new { param1 = "' + param1 + '", param2 = "' + param2 + '", param3 = "' + param3 + '" }, new AjaxOptions() { OnSuccess = "onSuccess" }, new { Class = "ABC" } ) %></li>');

Now the problem is that instead of the value of each of the param# variables being "inserted"...the variable name itself (e.g. param1) gets "inserted"...in other words the routeValues being posted to the controller action are param1, param2, and param3 instead of A, B, and C...does anyone know why this is happening and how to fix it?

Thanks D

Upvotes: 0

Views: 211

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

ActionLinks are useless in this case as they are server side code. You cannot mix them with client side javascript variables. Here's how I would do it (embracing the full power of jQuery):

$(function () {
    var param1 = 'A';
    var param2 = 'B';
    var param3 = 'C';
    $('ul#SomeUL').append(
        $('<li/>', {
            html: $('<a/>', {
                href: '<%= Url.Action("SomeAction") %>',
                text: 'Click Me',
                class: 'abc',
                click: function() {
                    var params = { 
                        param1: param1, 
                        param2: param2, 
                        param3: param3 
                    };
                    $.get(this.href, params, function(result) {
                        onSuccess();
                    });
                    return false;
                }
            })
        })
    );
});

Upvotes: 1

Related Questions