C# 如何将json数据发送到mvc控制器中的jsonresult函数?
我正在尝试将我的电子邮件和密码发送到我的家庭控制器jsonresult方法。 电子邮件和密码的值显示在第一个警报中,但当我将userCredential传递给数据时,它会显示警报undefined。 在ajax post方法中未传递电子邮件和密码的值C# 如何将json数据发送到mvc控制器中的jsonresult函数?,c#,json,ajax,asp.net-mvc,C#,Json,Ajax,Asp.net Mvc,我正在尝试将我的电子邮件和密码发送到我的家庭控制器jsonresult方法。 电子邮件和密码的值显示在第一个警报中,但当我将userCredential传递给数据时,它会显示警报undefined。 在ajax post方法中未传递电子邮件和密码的值 $("#button_val").click(function () { var userCrdential = "email=" + $("#username").val() + "&password="
$("#button_val").click(function () {
var userCrdential = "email=" + $("#username").val() + "&password="
+ $("#pwd").val();
alert(userCrdential);
$.ajax({
type: "POST",
url: "/Home/adduser",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: userCrdential,
success: function (res) {
// alert("data is posted successfully");
if (res.success == true)
alert("data is posted successfully");
else {
// alert("Something went wrong. Please retry!");
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusMessage);
}
});
});.
控制器
[HttpGet] public JsonResult adduser(user obj) { }
通过查看您的评论,我观察到的第一件事是,您在ajax调用上使用的是post方法,而在控制器级别,它是http get。这可能是问题所在。如果你也能为你的动作方法编写代码,那就好了 下面是mvc中通过ajax发布对象的示例
[HttpPost]
public ActionResult YourMethodName(MyViewModel myViewModel)
{
//your code goes here.
}
您可以像下面这样进行ajax调用
var requestData = {
Email: 'pass the email value here',
Password: 'pass the password value here')
};
$.ajax({
url: '/en/myController/YourMethodName',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
},
async: true,
processData: false
});
在控制器方法中使用
[HttpGet]
,但在ajax请求中使用POST
。因此,转到一个选项POST
或GET
。我使用GET
编写解决方案,首先使用以下命令更改控制器方法:
[HttpPost]
public JsonResult adduser(string email, string password) {
// work here
}
然后修改您的代码:
$("#button_val").click(function () {
var userCrdential = "email:"+ $("#username").val()+", password:"+ $("#pwd").val();
alert(userCrdential);
$.ajax({
type: "POST",
url: "/Home/adduser",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {userCrdential },
success: function (res) {
// alert("data is posted successfully");
if (res.success == true)
alert("data is posted successfully");
else {
// alert("Something went wrong. Please retry!");
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusMessage);
}
});
});
MVC控制器的签名方法是什么?[HttpGet]public JsonResult adduser(user obj){}//user是一个模型,其中我有电子邮件和密码属性。该方法是一个GET,您正在做一篇文章。你能把这个加到你的问题上吗。我会研究一下如何在MVC中正确地发布帖子。您也可以通过使用
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.POST)]
而不是[HttpGet]
来重新使用POST
的方法。感谢您的回复。但它给出了错误消息Unfinedi将GET请求更改为POST请求。