2015-08-27 38 views
7

因此讓我需要JS的對象,我所做的:通過AJAX發送對象的數組 - ASP.NET MVC

$('.combine-payment-input').each(function (index, value) { 
    if (parseFloat(value.value) > 0) { 
     if (methodOfPayment == -1) { 
      methodOfPayment = value.dataset.method; 
     } 
     else { 
      methodOfPayment = 0; 
     } 
     vmopl.push({ 
      id: value.dataset.method, 
      name: $('label[for="' + value.id + '"]').html(), 
      inUse: 'True', 
      ammount: value.value 
     }); 
    } 
}); 

如果我console.logvmopl到底,我就會得到這樣

[Object { id="2", name="Card", inUse="True", ammount="500"}, 
    Object { id="1", name="Cash", inUse="True", ammount="250"}] 

現在,如果我嘗試發送這AJAX這個了使用

$.get('/reports/savebill/' + methodOfPayment + '?vmop=' + JSON.stringify(vmopl), function (data) { 
    if (data == 'True') { 
     location.href = '/order/neworder/'; 
    } else { 
     alert("Unsuccessful!"); 
    } 
}); 

控制器動作應該vmop時,控制器看起來像這樣:

public bool SaveBill(int id, ViewMethodOfPayment[] vmop) { 
    //lots of code... 
} 

但是,當我把一個斷點,我總是看到vmop爲空,甚至當我把它傳遞到另一個對象(var temp = vmop;)。

ViewMethodOfPayment是一個簡單的模型類:

public class ViewMethodOfPayment 
{ 
    public long Id { get; set; } 
    public string Name { get; set; } 
    public bool InUse { get; set; } 
    public double Ammount { get; set; } 
} 

如果我錯過了任何信息,或者如果它是不清楚我想做/期望的,請留言,我會盡快我可以回答!

感謝您的閱讀!

編輯:改變的代碼的第一個塊(行:9,因爲我包括一個代碼,將帶來一個JavaScript錯誤)

+0

這將是很容易的,如果你只是序列化形式! –

+1

那麼如果你發送** POST **方法的數據呢:) –

+3

而不是'ViewMethodOfPayment [] vmop'嘗試放置'List vmop' –

回答

3

我目前使用的是:

Javascript通過JSON.stringify發送數據,就像你一樣。

C#:

public ActionResult AjaxDoSomething(string vmop) 
{ 
    var jss = new JavaScriptSerializer(); 
    try 
    { 
     var parameter = jss.Deserialize<ViewMethodOfPayment []>(vmop); 
     //Do something with this data and return the desired result 
     return Json(result, JsonRequestBehavior.AllowGet); 
    } 
    catch 
    { 
     return null; 
    } 
} 
+0

我想到了這一點,但純粹是因爲額外的步驟,這個Web服務不會在一個超快速的服務器上運行),我將它作爲最後的手段。 編輯:我現在正在閱讀編輯,接下來我會嘗試,可能會帶我幾個。 – NemanjaT

+1

好點,OP通常發送一個字符串,而不是一個數組,因爲他使用'JSON.stringify(vmopl)'。 –

+1

我不確定它是如何清晰地從這樣的評論,但它非常有效! (非常感謝你!)。 @TasosK。給了我一個澄清,說它已經是一個字符串了,所以我把它當作是這樣的(比如在你編輯參數的時候),然後把它寫成一個對象。再次感謝你! – NemanjaT

0

嘗試把[FromUri] ViewMethodOfPayment [] vmop之前如下面

public bool SaveBill(int id,[FromUri] ViewMethodOfPayment[] vmop) { 
//lots of code... 
} 
+0

將嘗試一點。 – NemanjaT

+0

[FromUri]不屬於任何已知的註釋庫?你從哪裏實施它? – NemanjaT

+0

如果你的控制器從ApiController繼承,你可以使用[FromUri] – VuongNQ