开发者

How to append Ajax.ActionLink using jQuery?

开发者 https://www.devze.com 2023-03-01 06:58 出处:网络
I\'m busy with a ASP.NET MVC 3 site. There should be a view with a list of links. The list is to be populated (or constructed, rather) using jQuery.

I'm busy with a ASP.NET MVC 3 site. There should be a view with a list of links. The list is to be populated (or constructed, rather) using jQuery.

Now, previously开发者_开发技巧 it worked by just saying in some javascript function (in a seperate javascript file):

$(ul#Items).append(<li><a href=...>...</a></li>);

for each item in an array.

But a change to the system now makes it necessary to utilize the functionality provided by Ajax.ActionLink. But if I try to append <%: Ajax.ActionLink ... %> like above, it actually appends it as text and not html (i.e. on the page it displays a list of <%: Ajax.ActionLink... <%>

Any suggestions why this is happening and how to make it work?

Thanks D


Isn't the following working:

$('ul#Items').append('<li><%= Ajax.ActionLink("Hello", "foo", new AjaxOptions {  }) %></li>');

Of course if you are using the Razor view engine:

$('ul#Items').append('<li>@Ajax.ActionLink("Hello", "foo", new AjaxOptions {  })</li>');

And don't forget that in ASP.NET MVC 3 by default jQuery is used by all Ajax.* helpers so you might need to include jquery.unobtrusive-ajax.js for the link to work.

This being said personally I wouldn't use Ajax.* helpers. Here's how I would do it:

$('ul#Items').append(
    $('<li/>', {
        html: $('<a/>', {
            href: '@Url.Action("someAction", "someController")',
            text: 'hello world',
            click: function () {
                $.get(this.href, function (result) {
                    alert('ajax success');
                });
                return false;
            }
        })
    })
);

UPDATE:

I didn't notice that you stated in a separate javascript file. That explains it. You cannot use server side tags in a static file.

0

精彩评论

暂无评论...
验证码 换一张
取 消