如何写在ASP.NET MVC中使用JavaScript操作链接? [英] How to write action links using javascript in ASP.NET MVC?

查看:114
本文介绍了如何写在ASP.NET MVC中使用JavaScript操作链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些追加行的表的脚本。其中一个行有一个删除链接,并为我使用的是ActionLink的,但是元素的ID是通过JS收到了,这也不是工作:

I have a script that appends some rows to a table. One of the rows has a delete link, and for that I am using a ActionLink, however the id of the element is received via js, and this is nor working:

 $("#Table").last().append('<tr><td><a href=\"<%:Html.ActionLink("Delete", "DeleteElementFromSet", new {id=%>Id<%})%>">Delete</a></td><td>'+Id+'</td></tr>');

其中id是从一个DropDownList的值获取其值一个javascript变量。

where Id is a javascript variable that gets its value from the value of a dropdownlist.

有没有办法使用ActionLink的这样一种方式?或做我必须手动写下来的路径?

Is there a way to use ActionLink like this? or do I have to write down the path manually?

推荐答案

由于该ID是在客户端,您将需要建立正确的URL唯一已知的。这是说从来没有混合C#和JavaScript。以下是你可能会如何进行:

Because the id is known only at the client side you will need to construct the proper url. This being said never mix C# and javascript. Here's how you might proceed:

通过声明一个全局变量,将持有的删除链接没有ID部分开始:

Start by declaring a global variable that will hold the delete link without the id part:

<script type="text/javascript">
    var deleteUrl = '<%: Url.Action("DeleteElementFromSet") %>';
</script>

,然后在独立 JavaScript文件:

and then in a separate javascript file:

$('#Table').last().append(
    $(document.createElement('tr'))
        .append($(document.createElement('td'))
            .append($(document.createElement('a'))
                .attr('href', deleteUrl + '/' + Id)
                .text('Delete')
            )
        )
        .append($(document.createElement('td'))
            .text(Id)
        )
);

注意,你应该使用 Url.Action 而不是 Html.ActionLink ,因为你已经有了手动生成锚

Notice that you should use Url.Action instead of Html.ActionLink because you already have the anchor manually generated.

注:避免使用GET动词删除。你可能有不好的惊喜。使用合适的动词(或至少POST)在服务器上修改状态,如删除时。

Remark: avoid using GET verbs for deleting. You might have bad surprises. Use proper verb (or at least POST) when modifying state on the server such as deleting.

这篇关于如何写在ASP.NET MVC中使用JavaScript操作链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆