mola10
mola10

Reputation: 986

Asp.net Mvc Ajax Json (post Array)

javascript\jQuery:

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

how to execute this code? thanks.

Upvotes: 4

Views: 15665

Answers (2)

roast_soul
roast_soul

Reputation: 3650

Try write code as below:

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

Upvotes: 0

Paul Creasey
Paul Creasey

Reputation: 28884

U can't pass mass: items and expect it to be serialized as a JSON array automatically, you will need to either iterate and construct the JSON (bad plan) or use a JSON library(good plan)

Upvotes: 1

Related Questions