kamyk
kamyk

Reputation: 295

AngularJS - Pass an array of objects to MVC Controller via $http

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?

Upvotes: 0

Views: 5184

Answers (3)

Karthik M R
Karthik M R

Reputation: 990

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

Upvotes: 2

Starfish
Starfish

Reputation: 3574

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

Upvotes: 0

Dilip Oganiya
Dilip Oganiya

Reputation: 1554

You have to put model here.

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

Upvotes: 0

Related Questions