2010-02-04 21 views
5

javascript \ jQuery:Asp.net MVC Ajax Json (po Array)

var items = new Array(); 

var obj { Begin: "444", End: "end" }; 

items.push(obj); 
items.push(obj); 

    var request = { 
      DateStart: $("#DateStart").val(), 
      mass: items 
     }; 


$.post("/Home/Index", request, null, 
"json"); 

C# MVC Index Controller

public class MyClass 
    { 
     public string Begin; 
     public string End; 
    } 

    [AcceptVerbs(HttpVerbs.Post)]   
    public ActionResult Index(   
     string DateStart,    
     MyClass []mass) 
    { 
     System.Diagnostics.Debug.WriteLine(mass[0].Begin); 
    } 

jak wykonać ten kod? dzięki.

+0

możliwe duplikat [jQuery Ajax wpis jest tablica do ASP.NET MVC kontroler] (http://stackoverflow.com/questions/4402036/jquery-ajax-posting-array-to-asp- net-mvc-controller) – Meryovi

+0

Tutaj jest prawo http://theycallmemrjames.blogspot.com/2010/05/aspnet-mvc-and-jquery-part-4-advanced.html – mola10

Odpowiedz

2

U nie może przejść mass: items i oczekiwać, iż zostanie automatycznie szeregowane jako tablicy JSON, trzeba będzie albo iteracji i skonstruować JSON (zły plan) lub użyć JSON library (dobry plan)

+0

+1 za dobry link. Funkcją do wykonania jest 'JSON.stringify (x)'. –

0

try write Kod poniżej:

var option = { 
    url: '/Home/Index', 
    type: 'POST', 
    data:JSON.stringify(request), 
    dataType: 'html', 
    contentType: 'application/json', 
    success: function (result) { alert(result); } 
    }; 
$.ajax(option);