我的页面上有这个链接:
@Html.ActionLink("Like", "Like", "Like", new {likeId = i.ItemId}, new {id = @i.ItemId, @class = "likeButton"})
这是我的 ajax 调用:
$(document).on("click", ".likeButton", function (event) {
var itemId = event.target.id;
$.ajax({
url: this.href,
type: 'POST',
data: { item: itemId },
context: this,
success: function (result) {
...
return false;
});
当动作梅托德像这样时,它就会起作用:
public ActionResult Like(int itemId)
...
但是如果我用[HttpPost]
装饰方法就行不通了。
这能实现吗?
另外,如果我不添加[HttpPost]
,会有什么安全问题?
试试这个:
$(document).on("click", ".likeButton", function (event) {
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
...
return false;
});
您正在传递项目。id 两次,第一次在 url 中,第二次在正文中。使用 POST 方法时,您仍然可以通过 URL 传递参数。当您想要隐藏这些参数时,使用 body 传递参数是很好的。
还有一件事,在这种情况下你可以使用Ajax.ActionLink(因为它是为这种情况创建的)
你有错误:
data: { item: itemId }
应该是:
data: { itemId: itemId },