MVC ajax发布到控制器动作方法

我一直在看这里的问题: MVC ajax json发布到控制器动作方法但不幸的是它似乎没有帮助我。 除了我的方法签名之外,我的情况几乎完全相同(但我已经尝试过,但它仍然没有被击中)。

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 } }); }); 

调节器

 [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, 

这是由于您发送了一个对象,并且您期望有两个参数。

试试这个,你会看到:

 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 } 

试试这个:

 /////// Controller post and get simple text value [HttpPost] public string Contact(string message) { return "

Hi,

we got your message,
" + message + "
Thanks a lot"; }

////在视图中添加对Javascript(jQuery)文件的引用

 @section Scripts{     } 

///然后添加Post方法如下:

  

现在让我们假设您想使用$ .Ajax和JSON来实现它:

 // Post JSON data add using System.Net; [HttpPost] public JsonResult JsonFullName(string fname, string lastname) { var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }"; //// you have to add the JsonRequestBehavior.AllowGet //// otherwise it will throw an exception on run-time. return Json(data, JsonRequestBehavior.AllowGet); } 

然后,在视图中:添加事件单击类型按钮的输入,甚至是来自提交:只需确保您的JSON数据格式正确。

  $("#jsonGetfullname").on("click", function () { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "@(Url.Action("JsonFullName", "Home"))", data: "{ \"fname\" : \"Mahmoud\" , \"lastname\" : \"Sayed\" }", dataType: "json", success: function (data) { var res = $.parseJSON(data); $("#myform").html("

Json data:

" + res.fname + ", " + res.lastname) }, error: function (xhr, err) { alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status); alert("responseText: " + xhr.responseText); } }) });

干杯,

马哈茂德赛义德

 $('#loginBtn').click(function(e) { e.preventDefault(); /// it should not have this code or else it wont continue //.... });