flo*_*bee 6 ajax jquery asp.net-mvc-3
这个问题已被多次询问,但我找到的解决方案似乎都没有起作用.让我觉得这可能是一个新问题,也许是ASP.NET MVC 3的特定内容.
我正在使用JQuery Ajax对ASP.NET MVC 3控制器进行简单调用.像这样
var addressInfo = {
Address1: "423 Judy Road",
Address2: "1001",
City: "New York",
State: "NY",
ZipCode: "10301",
Country: "USA"
};
$.ajax({
url: '/home/check',
type: 'POST',
data: JSON.stringify(addressInfo),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert("success");
},
error: function () {
alert("error");
}
});
Run Code Online (Sandbox Code Playgroud)
控制器看起来像这样
[HttpPost]
public ActionResult Check(AddressInfo addressInfo)
{
// Do something and return Json(something)
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,虽然它应该基于Scottgu的帖子的"JavaScript和AJAX改进"部分
我尝试了很多不同的变体,例如:
var args = new Object();
args.addressInfo = {
Address1: "423 Judy Road",
Address2: "1001",
City: "New York",
State: "NY",
ZipCode: "10301",
Country: "USA"
};
$.ajax({
url: '/home/check',
type: 'POST',
data: JSON.stringify(args),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert("success");
},
error: function () {
alert("error");
}
});
Run Code Online (Sandbox Code Playgroud)
然后直接使用JSON对象进行以上两种操作:
$.ajax({
url: '/home/check',
type: 'POST',
data: args,
success: function () {
alert("success");
},
error: function () {
alert("error");
}
});
Run Code Online (Sandbox Code Playgroud)
没有工作.如果我只有一个字符串,我传递给控制器,这是有效的.但是一旦我介绍了一个对象,我就无法让它工作.
任何人都知道可能是什么问题.
非常感谢您对此进行调查!
您的代码看起来不错,它应该可以工作。我刚刚在一个新应用程序中测试了以下内容,没有出现问题。
模型:
public class AddressInfo
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Check(AddressInfo addressInfo)
{
return Json(new { success = true });
}
}
Run Code Online (Sandbox Code Playgroud)
视图:
<script type="text/javascript">
var ai = {
Address1: "423 Judy Road",
Address2: "1001",
City: "New York",
State: "NY",
ZipCode: "10301",
Country: "USA"
};
$.ajax({
url: '/home/check',
type: 'POST',
data: JSON.stringify(ai),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8811 次 |
最近记录: |