简体   繁体   中英

ASP.NET Web API Controller Update Row

I'm having issues figuring out how to update just a single row in a controller in ASP.NET. I am trying to send a post request to the Web API I created and the request goes through but instead of updating only one row, it updates all rows (all rows in the column goal) in the table I am trying to manipulate in my SQL database. Any help with this problem would be appreciated. I am sending the post request using the $http service in AngularJS.

ASP.NET C#

    public class patient_goalsController : ApiController
    { 
        .
        .
        .

        //POST: api/goals/update/1
        [Route("Api/goals/update/{id}")]
        public void UpdatePatientGoal(int id, patient_goals patient_goals)
        {
            var goals = (from p_goal in db.patient_goals
                        where patient_goals.id == id
                        select p_goal);
            foreach(patient_goals row in goals)
            {
                row.goal = patient_goals.goal;
            }


        }

        .
        .
        .

   }

AngularJS

$scope.updateGoal = function(goal){
goal.editing = false;
console.log(goal.id);
var data = {"id": goal.id, "goal": goal.goal}
$http({
  method: "POST",
  url: urlBase + "/goals/update/" + goal.id,
  data: data,
}).then(function error(response) {
  $scope.error = response.statusText;
  console.log(response.statusText);
});

DB

id (int)
goal (text)

Just find the single connected entity you want, make the edits and then save your changes.

[Route("Api/goals/update/{id}")]
 public void UpdatePatientGoal(int id, patient_goals)
 {
      var goal =  db.patient_goals.FirstOrDefault(x => x.id == id);

      if(goal != null)
      {
          goal.goal  = patient_goals.goal;
          db.SaveChanges();
      }
  }

I don't really know the details of your database schema, but it looks like your where -clause is incorrect. Rather than comparing to patient_goals.id , you would be comparing to p_goal :

           var goals = (from p_goal in db.patient_goals
                        where p_goal.id == id
                        select p_goal);

Otherwise, you are simply comparing values from your parameter list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM