Search code examples
asp.net-mvcpostasp.net-mvc-routing

Route to a POST method with model and id


I want to pass in two Ids to my method. The method is called DeleteAttendee and is on my SessionController in the Training area.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteAttendee(int sessId, int attId)

I have created a link to get there that takes you to https://localhost:<port>/Training/Session/DeleteAttendee?sessId=1&attId=3.

<a asp-action="DeleteAttendee" asp-route-attId="@item.Attendee.Id" asp-route-sessId="@Model.Id">Delete</a>

Using the default routing, this page can't be found. What do I need to change or set up to route to this method?

Edit: Apparently the problem is that the link is performing a GET, but I need it to POST. How do I change it?

I think you can accomplish what I want to do with a button control. It will actually work better for me now if I can pass in the model and a specific id. I tried the button below. It looks correct in the markup, but the id keeps getting replaced with the sessionId when the button is clicked.

<button formaction="/Training/Session/DeleteAttendee/@item.Id" formmethod="post">Edit</button>

Solution

  • I ended up using a submit button that calls javascript and added the value to the viewmodel to get this done.

    On the page:

    <input type="hidden" asp-for="SelectedAttendeeId" />
    <input type="button" onclick="DeleteAttendee(@item.Id)" value="E" />
    

    In javascript:

    function DeleteAttendee(attendeeId) {
      var selectedAtt = $('#SelectedAttendeeId');
      selectedAtt.val(attendeeId);
      var model = $('#frmSession').serialize();
      $.post('/Training/Session/DeleteAttendee', model, function (data) {
        // success logic here
      });
    }