![](/img/trans.png)
[英]Post from JQuery Json to ASP.Net MVC: the 2 parameters are null
[英]data posted with jquery post to Asp.net 4 Mvc 2 as null
我正在使用jquery 1.8将数据发布到ASP.Net 4 MVC 2这样
PostData('Home/Login',{ "username": $("#username").val(),"password": $("#password").val()})
function PostData(url, data) {
$.ajax({
url: url,
data:data,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
Success:successFunction, Error: ErrorFunction
});
};
我的模特
namespace FmsMvc.Models
{
public class UsersModel
{
public int UserID { get; set; }
public string Role { get; set; }
public string Email { get; set; }
public DateTime ts { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
}
我的控制器
[HttpPost]
public JsonResult Login(UsersModel u)
{
if (doSomething(Prop1, Prop2)
return Json(null); // Success
return Json(new { Status:'success',Msg:" Your username"+u.username });
}
我的控制器未获取数据。 调试时为空。
我究竟做错了什么?
注意
我删除了Scripts文件夹中的所有JavaScript,因为我使用的是自定义脚本
在发布之前,您是否尝试过JSON.strinfigying您的数据?
function PostData(url, data) {
$.ajax({
url: url,
data:JSON.stringify(data),
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
Success:successFunction, Error: ErrorFunction
});
};
像这样尝试:
var data = { "username": $("#username").val(),
"password": $("#password").val()
};
PostData('Home/Login',JSON.stringify(data));
您可以使用JQuery .post()
方法为您解析值
var url = '@Url.Action("Login", "Home")'; // beter to use this rather than hardcoding
var userName = `$("#username").val();
var password = $("#password").val();
$.post(url, { Username: userName, Password: password }, function(result) {
// do something with the result you returned from the action method
alert(result.Msg);
});
注意,将仅在模型中设置属性“ Username
和“ Password
”。 其他属性将为其默认值。
经过大量调试后,我找到了罪魁祸首
在上面的我的ajax函数中,我有这两行
contentType: 'application/json; charset=utf-8',
dataType:'json',
以某种方式,这不应该。 当我提交带有两行的表单时,这就是我在chrome dev中看到的
但是当我删除行contentType: 'application/json; charset=utf-8'
contentType: 'application/json; charset=utf-8'
,因此$ .ajax现在是
$.ajax({ // create an AJAX call...
type: 'post', // GET or POST
url: url, // the file to call
dataType:'json',
data: data, // get the form data
Success:successFunction, Error: ErrorFunction
});
当我在提交后查看chrome dev时,我看到了,这是以前没有的
我不知道为什么会这样,我将尝试在其他浏览器中查看是否全部正常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.