0

I am trying to pass an array variable from ajax to controller, but I am not getting the values in controller

below is my code

AJAX

 function userDetailsClass() {
          var userDetails = {};
          userDetails.age = 12;
          userDetails.Name = "Vignesh";
          userDetails.lastName = "s";
          debugger;

          $.ajax({
              url: "Home/userDetails",
              data: JSON.stringify({
                  UserDetailsParam: userDetails
              }),
              responseType: "json",
              success: successfn,
              error: errorfn
          });
          function successfn(result) {

          };

          function errorfn(result) {

          };
      }

Controller

public ActionResult userDetails( string UserDetailsParam){
            return View();
        }

I also tried

public ActionResult userDetails( string[] UserDetailsParam){
            return View();
        }
3
  • 1
    I think you use the JSON.stringify the wrong way, you can find the detail spec from here, and when you want to transfer object to JSON, you just put the object in the method, as your example, JSON.stringify(userDetails) will return the JSON you want. Commented Dec 30, 2013 at 6:01
  • Sorry @winterfall I am a newbie to MVC and i am aware of how to pass models from ajax to controller Commented Dec 30, 2013 at 6:30
  • 1
    In my thinking, you want to send a JSON-format string to your server side, you named it with UserDetailsParam, and the real data is in the userDetails javascript object, JSON.stringify give you a method to transfer the javascript object to JSON-format string, so I think your code can change like this: UserDetailsParam: JSON.stringify(userDetails) Commented Dec 30, 2013 at 7:48

2 Answers 2

1

Your code should be like this

     $.ajax({
          url: "Home/userDetails",
          data: {
              "UserDetailsParam":JSON.stringify(userDetails)//change this
          },
          responseType: "json",
          success: successfn,
          error: errorfn
      });
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks ! :) In the controller I am not able to get an array if i deserialize the paramaeter passed!
i am also serializing parameters for sending like the way you are doing and by deserializing i was not able to get parameter as an array.
are you using the same code like this var array = new JavaScriptSerializer().DeserializeObject(UserDetailsParam);
i am using this Newtonsoft.Json dll for serializing and deserializing
0

Try with this

var userDetails = {"age":'12',"Name":'Vignesh',"lastName":'s'};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.