gpt4 book ai didi

c# - MVC ajax 发布到 Controller 操作方法

转载 作者:可可西里 更新时间:2023-11-01 07:54:47 25 4
gpt4 key购买 nike

我一直在看这里的问题:MVC ajax json post to controller action method但不幸的是,它似乎对我没有帮助。我的几乎完全一样,除了我的方法签名(但我已经尝试过了,但仍然没有成功)。

jQuery
$('#loginBtn').click(function(e) {
e.preventDefault();

// TODO: Validate input

var data = {
username: $('#username').val().trim(),
password: $('#password').val()
};

$.ajax({
type: "POST",
url: "http://localhost:50061/checkin/app/login",
content: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(data),
success: function(d) {
if (d.success == true)
window.location = "index.html";
else {}
},
error: function (xhr, textStatus, errorThrown) {
// TODO: Show error
}
});
});

Controller

[HttpPost]
[AllowAnonymous]
public JsonResult Login(string username, string password)
{
string error = "";
if (!WebSecurity.IsAccountLockedOut(username, 3, 60 * 60))
{
if (WebSecurity.Login(username, password))
return Json("'Success':'true'");
error = "The user name or password provided is incorrect.";
}
else
error = "Too many failed login attempts. Please try again later.";

return Json(String.Format("'Success':'false','Error':'{0}'", error));
}

但是,无论我尝试什么,我的 Controller 都不会被击中。通过调试,我知道它发送了一个请求,只是每次都得到一个Not Found错误。

最佳答案

您的 Action 需要字符串参数,但您发送的是复合对象。

您需要创建一个与您发送的内容相匹配的对象。

public class Data
{
public string username { get;set; }
public string password { get;set; }
}

public JsonResult Login(Data data)
{
}

编辑

此外,toStringify() 可能不是您想要的。只需发送对象本身。

data: data,

关于c# - MVC ajax 发布到 Controller 操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19663762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com