こちらの質問(https://stackoverflow.com/questions/4120212/mvc-ajax-json-post-to-controller-action-method)を拝見させていただきましたが、残念ながら私には役に立たないようです。私の場合は、メソッドのシグネチャ以外はほとんど同じです(でも、それを試してもヒットしませんでした)。
$('#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
}
});
});
[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)
{
}
EDIT (英語)
さらに、toStringify()はおそらくここでは必要ないでしょう。オブジェクト自体を送ればいいのです。
data: data,
それは、あなたが1つのオブジェクトを送信し、あなたが2つのパラメータを期待していることが原因です。
これを試してみるとわかります。
public class UserDetails
{
public string username { get; set; }
public string password { get; set; }
}
public JsonResult Login(UserDetails data)
{
string error = "";
//the rest of your code
}