2012-04-06 14 views
5

que tiene la siguiente clase de JavaScript que estoy tratando de pasar a un controlador de ASP.NET MVCgama Javascript para ASP.NET MVC controlador

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"; 

Así es como yo llamo el método de control:

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

En el lado del controlador he declarado un modelo de vista de la siguiente manera:

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

Mi controlador Guardar método es de Dicho de la siguiente manera:

public JsonResult Save(AttributeViewModel[] attributes) 

Cuando ejecuto el valor de los atributos siempre es nulo.

¿Alguna idea? No estoy seguro de cómo incluso comenzar a depurar esto.

Respuesta

6

Usted puede tratar de json.net biblioteca para resolver su 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

Gracias por la sugerencia. Se agregó una referencia a Json.net y se agregó el filtro, pero aún se pasa a los atributos. – Lance

+0

@Lance Respuesta actualizada con el código de cliente –

+0

Gracias Sanja, agregando JSON.stringify() trabajó un placer !! – Lance

1

parece que es necesario agregar traditional : true a la llamada AJAX. Eche un vistazo here y here

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

Agregado en tradicional: cierto, pero no resolvió el problema. He estado en esto por mucho tiempo, así que pasaré una matriz separada por comas al Controlador por ahora. – Lance

Cuestiones relacionadas