How to pass array data from angularjs to c# mvc model?

This is my model

public class StudentDataModel
{
    public StudentDataModel();

    [JsonProperty("student_data")]
    public StudentData Data { get; set; }
}



public class StudentData 
{
    public StudentData ();
    [JsonProperty("name")]
    public string Name { get; set; }
    public string Description { get; set; }
    public string Id { get; set; }
    [JsonProperty("active")]
    public bool IsActive { get; set; }

}

In javascript file i have students data like

  $scope.students=[];
$scope.saveStudent=function(){
 return $http.post("/Student/Save?studentData=" + $scope.students)
        .then(function (result) {

        });
};

In students array contains number of students.

Mvc code:-

public async Task<JsonNetResult> Save(List<StudentData> studentData )
    {
       return new JsonNetResult { Data = response };
    }

In the above code i want to pass students array to mvc controller. mvc controller was hitted but data was not passed.

Upvotes: 0

Views: 4277

Answers (2)

Sajal
Sajal

Reputation: 4401

Create a request class, and pass those parameters form the UI

$scope.saveStudent=function(){
var inData = {'Students': JSON.stringify($scope.students)};
 return $http.post("/Student/Save?studentData=", inData )
        .then(function (result) {

        });
};

A DTO class for the request:

public class StudentDto
{
  public string Students;
}

Then in the MVC Controller:

public async Task<JsonNetResult> Save(StudentDto request )
{
   var studentList = JsonConvert.DeseralizeObject<>(request.Students).ToList();     
}

Upvotes: 2

Satpal
Satpal

Reputation: 133403

You should send $scope.students as data i.e. Request content of method $http.post(url, data, [config]);

$http.post("/Student/Save", $scope.students);

Upvotes: 0

Related Questions