0

I'm wondering a long time and I can't find a solution, maybe someone of you resolved a similar problem.

Let's say we want to pass and array of objects via $http service to the MVC Controller. This array is created in angular so I don't know the proper type (just var). The problem is I don't know what type of parameter should be in MVC function

AngularJS Controller

$scope.DoSth = function (){
    var data = [{
        Id: "1",
        Value: "apple"
    },
    {
        Id: "2",
        Value: "banana"
    }];
};

//DoSthService injected into angular controller

DoSthService.doSth(data)
    .success(function(result){
        //sth with success result
    })
    .error(function(result){
        //sth with error result
    });

AngularJS Service:

this.doSth = function(data){
    var response = $http({
        method: "post",
        url: "Home/DoSth",
        data: data
        //or data: JSON.stringify(data) ??
        });
    return response;
};

MVC Controller:

public string DoSth(**what type here?** data)
{
    //do sth and return string
}

Could anyone help me?

1
  • You need something like jackson to map json to a pojo. Commented Apr 21, 2016 at 11:41

3 Answers 3

2

Create a class

public class  MyClass
{
  public int Id { get; set;}
  public string Value { get; set;}
}

use the list in your method

public string DoSth(List<MyClass> data)
{
    //access your data
    //data[0].Id,data[0].Value or by any other way
}

No need to change any of your js code

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Happy coding!
0
You have to put model here.

public string DoSth(FruitModel  data)
{
    //do sth and return string
}

1 Comment

Thanks for the answer, Karthik M R's answer was more precise
0

If I'm not mistaken you can do this with a stringtype (if JSON is sent)

public string DoSth(string data)
{
    //do sth and return string
}

Don't forget to add this header in your AJAX request:

headers: {
   'Content-Type': 'application/json'
}

Also stringify it, like:

data: JSON.stringify(data)

If you did it right your AJAX request should look like this:

this.doSth = function(data){
    var response = $http({
            method: 'post',
            url: 'Home/DoSth',
            headers: {
               'Content-Type': 'application/json'
            },
            data: JSON.stringify(data)
        });
    return response;
};

1 Comment

Thanks for the answer, I checked it but I still received null object, don't know why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.