简体   繁体   中英

Calling Controller method from view

I feel this is a really simple problem, but I can't figure out how to do it.

I have a webpage with log entries for each exercise I do in the gym. Date, exercise, weight, reps etc. I can add entries. And I also want to delete a line from the index page by pressing a button. I just want the line to be deleted after clicking delete once and still stay in the index page. But, I don't know how to call my delete method from the index view page.

I added some pseudocode in the last column

        <tbody>
        @foreach (var logrow in Model.Take(30))
        {
            <tr>
                <td>
                    <h6>@logrow.Date.ToString("dd-MM-yy")</h6>
                </td>
                <td>
                    <h6>@logrow.Exercise</h6>
                </td>
                <td>
                    <h6>@logrow.Weight</h6>
                </td>
                <td>
                    <h6>@logrow.Repetitions</h6>
                </td>
                <td>
                    <h6>@logrow.Sets</h6>
                </td>
                <td>
                    <h6>@logrow.Rest_time</h6>
                </td>
                <td>
                    <h6>@logrow.Notes</h6>
                </td>
                <td>
                    <*LINK TO METHOD DELETE_LOG_ROW(logrow.id)* class="btn btn-danger btn-sm">
                        <span class="glyphicon glyphicon-trash"></span><span class="hidden-xs"> Delete</span>
                    </a>
                </td>
            </tr>
        }
    </tbody>
Html.ActionLink("Delete", "ActionName", "ControllerName", new { id = logrow.YourID }, null)

In controller

public ActionResult ActionName(int id)
{
    // delete logic
    return View("ViewName", "ControllerName");

}

You can't do this without page reload in pure ASP.NET MVC. Use AJAX to prevent this reload.

So your flow looks like

  • Call server via ajax to delete entity

  • Call server again to get updated entities collection

  • Rebuild DOM

您可以调用ajax并删除所需的项,并从服务器获取更新的列表,然后以局部视图或Json的形式返回它,并在显示列表的位置重新绑定div。

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