2015-04-12 21 views
1

我AngularJs POST請求:後數據使用AngularJS到MVC上Service.js 2.0

this.Add = function (employee) { 
     var response = $http({ 
      method: "post", 
      url: "/Employee/Add", 
      data: JSON.stringify(employee), 
      dataType: "json", 
     }); 
     return response; 
    } 

我莫代爾類:

[Serializable] 
    public class Employee 
    { 
     public Employee() 
     { } 
     public int ID { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public string UserName { get; set; } 
     public string Password { get; set; } 
    } 

添加EmployeeController的方法:

[HttpPost] 
     public string Add(Employee employeeNew) 
     { 
       if (employeeNew != null) 
       { 
        unitOfWork.EmployeeRepository.Insert(employeeNew); 
        unitOfWork.Save(); 
        return "Record has been Added"; 
       } 
       else 
       { 
        return "Record has Not been Verified"; 
       } 
     } 

我使用MVC 2.0。當我在上面提出請求時,Add方法中的Employee類是空的。另一方面,當我查看我的添加請求時,我看到該請求包含名字,姓氏,用戶名和密碼值以及完整的正確數據。如何將這些屬性綁定到Add方法的Employee對象上。

+0

我有同樣的問題..但我從'.apsx'頁面'.cshtml'頁面切換。它解決了我的問題,我知道它不適合做這件事..但仍然這是workaroud –

回答

0

$ http是一個異步請求。這意味着這個請求的返回由promis組成,這是在請求完成並且方法接收到數據後您可以執行的。你必須使用回調來處理這個promis。嘗試:

this.Add = function (employee) { 
    var response = {} 

$http({ 
     method: "post", 
     url: "/Employee/Add", 
     data: JSON.stringify(employee), 
     dataType: "json", 
    }).succes(function(data){ 

     response = data; 

    }).error(function(){ 

     //Handle errors caused by the HTTP-request 

    }) 
} 
+0

我可以做到這一點,但我的問題是關於將PostValues綁定爲一個Employee類對象。我的角度控制器文件是這樣的。 $ scope.Save =函數(){ VAR僱員= { 姓:$ scope.FirstName, 名字:$ scope.LastName, 用戶名:$ scope.UserName, 密碼:$ scope.Password }; var getMSG = angularService.Add(Employee); – user2762782

相關問題