将ajax的值传给控制器,ASP.Net C#MCV - 将值从Ajax Jquery传递给Controller(示例代码)

我需要将一个值从前端传递给控制器​​,我很难让它传递值。

阿贾克斯/ jQuery的

//unlock user account

$("#results").on('click', ".unlockactionbutton", function (e) {

e.preventDefault();

var userid = this.getAttribute("userid");

if (envdd.children(':selected').val() == "") {

alert("Please select User");

} else {

alert(userid);

$.ajax({

type: "GET",

url: "@Url.Action("UnlockUser", "Home", new { userid = userid })",

//Url.Action("UnlockUser", "Home", new { id = userid });

contentType: "application/json; charset=utf-8",

dataType: "json",

data: JSON.stringify(userid),

success: function (data) {

console.log(data);

},

error: function(data) {

alert('error');

console.log(data);

}

});

}

});

这是ActionResult。我有代码只是在控制台中发表评论,所以我可以看到它现在有效。

[HttpPost]

public ActionResult UnlockUser(string userid)

{

if (userid != "")

{

return Json("success - call from HomeController", JsonRequestBehavior.AllowGet);

}

else

{

return Json("error", JsonRequestBehavior.AllowGet);

}

}

答案

控制器动作用HttpPost装饰,但你在ajax发送一个GET请求,将类型改为type: 'POST',。

发出POST请求时,无需将数据附加到查询字符串。

此外,如果您指定application/json,请确保在发送字符串时发送json。因此,您可以删除行contentType: "application/json; charset=utf-8",或将数据参数更改为data: JSON.stringify({ userid: userid })。

您的ajax请求可能如下所示:

$.ajax({

type: "POST",

url: "@Url.Action("UnlockUser", "Home")",

dataType: "json",

data: JSON.stringify(userid),

success: function (data) {

console.log(data);

},

error: function(data) {

alert('error');

console.log(data);

}

});

要么

$.ajax({

type: "POST",

url: "@Url.Action("UnlockUser", "Home")",

contentType: "application/json; charset=utf-8",

dataType: "json",

data: JSON.stringify({ "userid" : userid }),

success: function (data) {

console.log(data);

},

error: function(data) {

alert('error');

console.log(data);

}

});

另一答案

在您的ajax请求中,您使用的是动词GET,您的操作是POST方法。

另一答案

尝试这样的事情,这将有效:

$("#results").click(function (){

var userid = this.getAttribute("userid");

$.ajax({

type: "POST",

url: "/Home/UnlockUser",

"data": "{userid:'" + userid + "'}",

contentType: "application/json; charset=utf-8",

dataType: "json",

success: function (data) {

console.log(data);

}

});

})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值