发布.net MVC 3 FromsCollection从其他领域与jQuery的ajax
好吧,我完全是新的.NET MVC3,我遇到了一个问题。发布.net MVC 3 FromsCollection从其他领域与jQuery的ajax
我正在开发一个使用Jquery mobile的移动应用程序,我希望将数据从移动应用程序发送到网页。在服务器上我有这样的:
[HttpPost]
[ValidateInput(true)]
public ActionResult Save(FormCollection actionValues) {
int age = Int32.Parse(actionValues["age"]);
string fn = actionValues["first_name"];
string ln = actionValues["last_name"];
CreateAndStorePersonModel(age,fn,ln); // Dummy method, not important
return new HttpStatusCodeResult(200); // Thanks to 3nigma for this
}
我要的是能够得到actionValues并将其存储在一个模型,那么这种模式存储到数据库中。为了这个例子,我们假设我想存储一个“Person”,其属性为:“first_name,last_name,age”。另外我可能会在未来扩展这个模型。
从移动应用程序,我运行下面的代码:
$.ajax({
type: "POST",
url: "http://external.url/Save",
dataType: "json",
traditional: true, // default serialization (do I even need this?)
data: {
"age": data_age,
"first_name": data_fn,
"last_name": data_ln,
},
success: function(d) { alert("Success: "+d},
}).error(function(data, errorTxt, jqXHR) {
alert('Error: '+errorTxt);
});;
我得到了500内部错误,但由于3nigma这不再是这种情况。
编辑:
当从我的web服务器测试我得到一个HTTP 302“找到”检查检查的时候,但数据不会保存。在编译到手机时,.error处理程序会带来“parseerror”,但数据会被保存。任何想法为什么?
答:
302“发现”出来,因为我回一个视图(感谢3nigma)应该返回此:
return new HttpStatusCodeResult(200);
500内部服务器错误
public ActionResult Save(FormCollection actionValues) {
int age = long.Parse(actionValues["age"]);// there error seems to be here you are boxing long into int
string fn = actionValues["first_name"];
string ln = actionValues["last_name"];
CreateAndStorePersonModel(age,fn,ln);
}
尝试,而不是
int age = Int32.Parse(actionValues["age"].ToString());
回答评论
你不需要有任何距离的ActionResult返回JSON像
[HttpPost]
public ActionResult Save(FormCollection actionValues) {
//your code here
return Json(new {IsSuccess="success" });
}
,并在阿贾克斯成功处理程序,您可以访问它像
$.ajax({
type: "POST",
url: "http://external.url/Save",
dataType: "json",
traditional: true, // default serialization (do I even need this?)
data: {
"age": data_age,
"first_name": data_fn,
"last_name": data_ln,
},
success: function(data) {
alert("Success: "+data.IsSuccess}, //will alert Success: success
}).error(function(data, errorTxt, jqXHR) {
alert('Error: '+errorTxt);
});;
它可以是产生问题
您的JSON数据语法data:
{
"age" : intValue,
"first_name" : stringValueinSingleQuotes,
"last_name" : stringValueinSingleQuotes
}
你可以有更多的成功:$ .ajax调用中的Handler()属性。如果调用成功,则会调用Handler()方法。
投入大,但它不是导致问题的数据字段。但是,将成功处理程序添加到ajax调用是一件好事。这样我就不需要像jsonp那样做。所以,谢谢:) – Sindre 2012-03-08 13:10:33
啊哈哈,我编辑了我的帖子。谢谢。有点刚刚在我头顶上键入。但是CORS不应该像我那样有问题,对吧? – Sindre 2012-03-08 16:40:17
如果你在响应中设置了appropraite接受标题,可能也不会,你也应该编辑这个问题,不要在早些时候改变你的内部服务器错误,现在你已经删除它... – Rafay 2012-03-08 18:25:29
啊,真的。我是这个网站的新手,非常抱歉。 – Sindre 2012-03-08 18:30:54