2012-03-08 69 views
1

好吧,我完全是新的.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); 

回答

3

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

啊哈哈,我編輯了我的帖子。謝謝。有點剛剛在我頭頂上鍵入。但是CORS不應該像我那樣有問題,對吧? – Sindre 2012-03-08 16:40:17

+0

如果你在響應中設置了appropraite接受標題,可能也不會,你也應該編輯這個問題,不要在早些時候改變你的內部服務器錯誤,現在你已經刪除它... – Rafay 2012-03-08 18:25:29

+0

啊,真的。我是這個網站的新手,非常抱歉。 – Sindre 2012-03-08 18:30:54

0

它可以是產生問題

您的JSON數據語法
data: 
{ 
    "age"   : intValue, 
    "first_name" : stringValueinSingleQuotes, 
    "last_name" : stringValueinSingleQuotes 
} 

你可以有更多的成功:$ .ajax調用中的Handler()屬性。如果調用成功,則會調用Handler()方法。

+1

投入大,但它不是導致問題的數據字段。但是,將成功處理程序添加到ajax調用是一件好事。這樣我就不需要像jsonp那樣做。所以,謝謝:) – Sindre 2012-03-08 13:10:33