0

В этом коде cshtml формируется таблица работников. В конце каждой строки кнопка "Удалить". Что необходимо добавить, чтобы кнопка "Удалить" вызывала нужный метод в контроллере?

@foreach (var b in ViewBag.Workers)
{
    <tr>
        <td><p>@b.Surname</p></td>
        <td><p>@b.Name</p></td>
        <td><p>@b.Patronymic</p></td>
        <td><p>@b.Position</p></td>
        <td>
            <form method="post" action="">
                <input type="hidden" value="@b.Id" name="WorkerId" />
                <input type="submit" value="Удалить" />
            </form>
        </td>
    </tr>
}

1 ответ 1

0

С jQuery, будет вроде этого:

@foreach (var b in ViewBag.Workers)
{
    <tr>
        <td><p>@b.Surname</p></td>
        <td><p>@b.Name</p></td>
        <td><p>@b.Patronymic</p></td>
        <td><p>@b.Position</p></td>
        <td>
            <button data-id="@b.Id">Удалить</button>
        </td>
    </tr>
}

...

<script>
'use strict';

var urlToAction = '@Url.Action("RemoveItPlease", "Home")';

$(document).ready(function() {
    $('table button').click(function (e){
        var workerId = $(e.target).data('id');

        $.ajax({
            url: urlToAction,
            method: 'POST',
            data: { id: workerId }
        });
    });
});

</script>

....

public HomeController: Controller {
    [HttpPost]
    public ActionResult RemoveItPlease(int id) {     
        ...
    }
}

Обработку ошибок и обновление таблицы оставляю за скобками.

2
  • Используя данный код, в строке var workerId = e.target.data('Id'); возникает ошибка Uncaught TypeError: e.target.data is not a function 2 ноя 2017 в 14:56
  • @РыбаковГригорий, да, точно. Поправил ответ.
    – free_ze
    2 ноя 2017 в 15:03

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.