0

I am sending an id and a list from angular to C# web API, but it is received by null when debugging the method, without knowing the reason.

angular service

this.deletevacs = function (staffid, vacs) {
    return $http.post("/AssignUserToDepartmentapi/api/assignuser/deletevacs?staffid=" + staffid + '&vacs=' + JSON.stringify(vacs))
}

angular js

var result = DevExpress.ui.dialog.confirm("Are you sure want to delete vacations assigned employees ?", "Confirm changes");
        result.done(function (dialogResult) {
            if (dialogResult) {

                var promisePost = Assignments.deletevacs($scope.SelectedEmp1.staffkey, $scope.oldvacs);
                promisePost.then(function (pl) {
                    toastr.success("Successfully deleted");

C#

[HttpPost]
    public HttpResponseMessage deletevacs(int staffid,int[] vacs)
    {
        try
        {
            obj.ExecNonQuery(string.Format("delete from HR_AssRole_Dep where staff_key={0} and Role=7 and Current_Flag=1 and VacMKey ={1}"
                           , staffid
                           , vacs));


        }
        catch (Exception ex)
        {


        }
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        return response;
    }

any help, thanks in advance

new C#

[HttpPost]
    public HttpResponseMessage deletevacs([FromBody] role r)
    {

                    obj.ExecNonQuery(string.Format("delete from HR_AssRole_Dep where staff_key={0} and Role=7 and Current_Flag=1 and VacMKey ={1}"
                              ,r.Staff_Key
                              , r.VacMKey));





        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        return response;
    }

class

 public class role
{
    //public int Ass_Dep_Key { get; set; }
    public int Dep_Key { get; set; }
    public int Staff_Key { get; set; }
    public int Role { get; set; }
    public List<int> VacMKey { get; set; }
    public short SelfApprov { get; set; }
}

new angular

var deletevacssss = { Staff_Key: $scope.SelectedEmp1.staffkey, VacMKey: $scope.selectedvacs };

        var result = DevExpress.ui.dialog.confirm("Are you sure want to delete vacations assigned employees ?", "Confirm changes");
        result.done(function (dialogResult) {
            if (dialogResult) {



                var promisePost = Assignments.deletevacs(deletevacssss);
                promisePost.then(function (pl) {
                    toastr.success("Successfully deleted");

new angular service

this.deletevacs = function (deletes) {
return $http.post("/AssignUserToDepartmentapi/api/assignuser/deletevacs", deletes)
}

when i make a debug, the r object from role class get the staffkey from angular correctly but the list of vacmkey count by 0 ???

hassanzi
  • 191
  • 17
  • Possible duplicate of [Passing List of Integers to GET REST API](https://stackoverflow.com/questions/27957785/passing-list-of-integers-to-get-rest-api) – Ramesh Rajendran Mar 11 '19 at 11:08

2 Answers2

0

Solution 1:

Use [FromUri] attribute in your HttpPost method parameter since you are getting the value from the querystring in the Url.

Try this:

[HttpPost]
public HttpResponseMessage deletevacs([FromUri]int staffid, [FromUri] int[] vacs)
{
    try
    {
    obj.ExecNonQuery(string.Format("delete from HR_AssRole_Dep where staff_key={0} and Role=7 and Current_Flag=1 and VacMKey ={1}"
               , staffid
               , vacs));
    }
    catch (Exception ex)
    {
    }
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}

Solution 2: Create an object that contains the staffId and vacs properties and assign it to the parameter. Add the [FromBody] attribute to before the object parameter. Then in your httpPost call, put the parameter inside the body of the request instead of the Url.

Google about the use of [FromBody] in webapi.

Solution 3:

Istead of using HttpPost, why not use HttpDelete method. It is clear in your problem that your intention is to delete records. In web API, you can use the HttpDelete attribute instead of HttpPost. To do this, change your attribute to HttpDelete from HttpPost, and in your paramter, you can just pass the [FromUri] int StaffId only and inside your API, all the vacs record related that StaffId, you can delete programmatically in DB. When calling your API use the $http.delete endpoint method instead.

  • first of all, thanks lot for reply. i tried the first solution , but now vacs returned 0 not "null", when i tried the second solution i got error 500 er[object object]. any idea – hassanzi Mar 11 '19 at 10:58
  • Try creating a class for the request body. – John Carlo Diocadiz Mar 11 '19 at 10:59
  • [HttpPost] public HttpResponseMessage deletevacs([FromBody] VacsInfo vacs) { try { obj.ExecNonQuery(string.Format("delete from HR_AssRole_Dep where staff_key={0} and Role=7 and Current_Flag=1 and VacMKey ={1}" , staffid , vacs)); } catch (Exception ex) { } HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); return response; } – John Carlo Diocadiz Mar 11 '19 at 11:01
  • Public Class VacsInfo { int StaffId {get;set;}, int[] vacs {get;set;} } – John Carlo Diocadiz Mar 11 '19 at 11:02
  • Instead of using HttpPost, why not use HttpDelete method. In your HttpDelete method, you can just pass the StaffId and all the vacs record related that StaffId, you can manipulate in web API and delete them programmatically in DB. So Instead of passing two parameters, you can pass one param which is the staffId. – John Carlo Diocadiz Mar 11 '19 at 11:09
  • [HttpDelete] public HttpResponseMessage deletevacs(role r) { try { obj.ExecNonQuery(string.Format("delete from HR_AssRole_Dep where staff_key={0} and Role=7 and Current_Flag=1 and VacMKey ={1}" , r.Staff_Key , r.VacMKey)); } catch (Exception ex) { } HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); return response; } still the problem exist . – hassanzi Mar 11 '19 at 11:17
  • Is VacMKey type of int[] or just int? – John Carlo Diocadiz Mar 11 '19 at 11:26
  • If you are only using two int parameters you can use the querystring in your endpoint calls. In your api code try this. [HttpDelete] public HttpResponseMessage deletevacs([FromUri] int staffId, [FromUri] int vacMKey) { **your code here**} – John Carlo Diocadiz Mar 11 '19 at 11:29
  • it is int [] vac – hassanzi Mar 11 '19 at 11:32
  • What is the data type of column "VacMKey" in your HR_AssRole_Dep table? – John Carlo Diocadiz Mar 11 '19 at 11:35
  • it is smallint . – hassanzi Mar 11 '19 at 11:40
  • Since it is a small int, then it can only contain one value right? However, in your code you are trying to pass an array of int using this syntax: int[] vacs. This is incorrect, instead use Int16 vacs. Is VacMKey a foreign key? See ref. https://stackoverflow.com/questions/425389/c-sharp-equivalent-of-sql-server-datatypes – John Carlo Diocadiz Mar 11 '19 at 11:44
  • yes it is. i tried to use int16[] or short[] but sill the value = null, but when i put [fromuri] it becomes 0, any idea, thanks – hassanzi Mar 11 '19 at 17:00
  • remove the "[]" in your Int16 data type. Adding open and close bracket such as this "[]" after your data type declaration will convert it to type array. Since you mentioned that it is a small int in DB, you should use Int16. You should declare it like this: Int16 vacs = 0; Not like below int16[] vacs = 0; – John Carlo Diocadiz Mar 12 '19 at 05:35
  • i made an update,please look at it in the upper page, i used the class – hassanzi Mar 12 '19 at 09:25
0

you should pass the parameter values for post method in params property .

var data = {staffid: staffid, vacs:vacs};
    $http({
      url: "/AssignUserToDepartmentapi/api/assignuser/deletevacs",
      method: "POST",
      params: data
    })

or try this below way

var data = {staffid: staffid, vacs:vacs};
    $http.post("/AssignUserToDepartmentapi/api/assignuser/deletevacs", data ).then(function (data, status, headers, config) { 
    alert("success"); 
},function (data, status, headers, config) { 
    alert("error"); 
});

API code should be like

[HttpPost]
public HttpResponseMessage deletevacs([FromUri]int staffid, [FromUri] int[] vacs)
{

...

}
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234