Home > database >  Payload is not passed to the handler
Payload is not passed to the handler

Time:01-05

I'm currently working on a small example web application. I would like to send the id from a table to the appropriate post handler with an Ajax call. I get to the handler but somehow the payload gets lost along the way. The developer tools (network) correctly output the ID in the payload section. However, only a 0 arrives in the post handler.

In addition, I would also find it interesting how I could pass an entire object to the Ajax function.

Thanks in advance for the help.

View

foreach (var student in Model.Students)
{
    <tr>
        <td>@student.StudentId</td>
        <td>@student.Salutation</td>
        <td>@student.FirstName</td>
        <td>@student.LastName</td>
        <td>@student.EmailAddress</td>
        <td>@student.City</td>
        <td>@student.CreatedOn.ToString("ddd., dd.MM.yyyy")</td>
        <td>
            <a  onclick="DeleteStudentRecord(@student.StudentId)">Delete</a>
        </td>
    </tr>
}

Ajax script

function DeleteStudentRecord (studentId) {
   $.ajax({
      type: "POST",
      url: '@Url.Action("DeleteStudentRecord", "Students")',
      data: {StudentId: studentId},
      dataType: "json"
   });
}

Post handler (StudentsController.cs)

[HttpPost]
public IActionResult DeleteStudentRecord(int id)
{
    StudentViewModel viewModel = new();

    _studentService.DeleteStudent(id);

    viewModel.Students = _studentService.GetAllStudents();
    ModelState.Clear();

    return View("StudentsList", viewModel);
}

CodePudding user response:

Ajax script must be like :

    function DeleteStudentRecord (studentId) {
   $.ajax({
      type: "POST",
      url: '@Url.Action("DeleteStudentRecord", "Students")',
      data: {id: studentId},
      dataType: "json"
   });
}

Because in your Students controller DeleteStudentRecord action wait for id and not for StudentId.

or you can change id to StudentId in your DeleteStudentRecord action.

  •  Tags:  
  • Related