C# MVC ajax post到控制器动作方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19663762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC ajax post to controller action method
提问by ediblecode
I've been looking at the question here: MVC ajax json post to controller action methodbut unfortunately it doesn't seem to be helping me. Mine is pretty much the exact same, except my method signature (but I've tried that and it still doesn't get hit).
我一直在看这里的问题:MVC ajax json post to controller action method但不幸的是它似乎并没有帮助我。我的几乎完全相同,除了我的方法签名(但我已经尝试过了,它仍然没有被击中)。
jQuery
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));
}
However, no matter what I try, my Controller
never gets hit. Through debugging, I know that it sends a request, it just gets a Not Found
error each time.
但是,无论我尝试什么,我都Controller
不会被击中。通过调试,我知道它发送了一个请求,但Not Found
每次都会出错。
采纳答案by David L
Your Action is expecting string parameters, but you're sending a composite object.
您的 Action 需要字符串参数,但您发送的是复合对象。
You need to create an object that matches what you're sending.
您需要创建一个与您发送的内容相匹配的对象。
public class Data
{
public string username { get;set; }
public string password { get;set; }
}
public JsonResult Login(Data data)
{
}
EDIT
编辑
In addition, toStringify() is probably not what you want here. Just send the object itself.
此外,toStringify() 在这里可能不是您想要的。只需发送对象本身。
data: data,
回答by Chris Dixon
It's due to you sending one object, and you're expecting two parameters.
这是因为您发送了一个对象,而您需要两个参数。
Try this and you'll see:
试试这个,你会看到:
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
}
回答by jason
$('#loginBtn').click(function(e) {
e.preventDefault(); /// it should not have this code or else it wont continue
//....
});
回答by mahmoud
try this:
尝试这个:
/////// Controller post and get simple text value
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
//// in the view add reference to the Javascript (jQuery) files
//// 在视图中添加对 Javascript (jQuery) 文件的引用
@section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
/// then add the Post method as following:
/// 然后添加 Post 方法如下:
<script type="text/javascript">
/// post and get text value
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
//// empty post('') means post to the default controller,
///we are not pacifying different action or controller
/// however we can define a url as following:
/// var url = "@(Url.Action("GetDataAction", "GetDataController"))"
.done(function (response) {
$("#myform").html(response);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});
Now let's say you want to do it using $.Ajax and JSON:
现在假设您想使用 $.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);
}
Then, inside your view: add the event click on a an input of type button, or even a from submit: Just make sure your JSON data is well formatted.
然后,在您的视图中:添加事件单击类型按钮的输入,甚至来自提交:只需确保您的 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("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});
cheers,
干杯,
Mahmoud Sayed
马哈茂德赛义德