2012-04-06 34 views
5

Ho la seguente classe di javascript che sto cercando di passare a un ASP.NET MVC controllerPassando serie Javascript per ASP.NET MVC controller

var postParams = { 

     attributes : [ 
         { 
          name : '', 
          description: '', 
          attributeType : '', 
          value : '' 
         } 
         ] 
    }; 

postParams.attributes[0] = new Object(); 
postParams.attributes[0].name = "test"; 
postParams.attributes[0].description = "test"; 
postParams.attributes[0].attributeType = "test"; 
postParams.attributes[0].value = "test"; 

Ecco come chiamo il metodo di controllo:

var actionURL = "@Url.Action("Save", "Catalog")"; 
    $.ajax({ 
        type: "POST", 
        url: actionURL, 
        data: postParams ...... 

Sul lato controller che ho dichiarato un ViewModel come segue:

public class AttributeViewModel 
{ 
    public string name { get; set; } 
    public string description { get; set; } 
    public string attributeType { get; set; } 
    public string value { get; set; } 
} 

mio controller Salva metodo è de clared come segue:

public JsonResult Save(AttributeViewModel[] attributes) 

Quando eseguo il valore di attributi è sempre nullo.

Qualche idea? Non sai come iniziare a eseguire il debug di questo.

risposta

6

Si può provare json.net libreria per risolvere il tuo problema

[JsonFilter(Param = "attributes", JsonDataType = typeof(AttributeViewModel[]))] 
    public JsonResult Save(AttributeViewModel[] attributes) 

Al cliente:

$.ajax({ 
     type: 'POST', 
     url: url, 
     async: true, 
     data: JSON.stringify(attributes), //!!! Here must be the same name as in controller method 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     success: function (data) { 

     }, 
     error: function (xhr, ajaxOptions, thrownError) { 

     } 
    }); 
+0

Grazie per il suggerimento. Aggiunto un riferimento a Json.net e aggiunto il filtro ma null è ancora passato agli attributi. – Lance

+0

@Lance Risposta aggiornata con il codice cliente –

+0

Grazie Sanja, l'aggiunta di JSON.stringify() ha funzionato bene! – Lance

1

Sembra come è necessario aggiungere traditional : true alla chiamata AJAX. Date un'occhiata here e here

$.ajax({ 
       traditional: true, 
       type: "POST", 
       url: actionURL, 
       data: postParams 
+0

Aggiunto nel tradizionale: vero ma non ha risolto il problema. Sono stato su questo per troppo tempo quindi passerò in una matrice separata da virgola al controller per ora. – Lance