首页 > 解决方案 > 表单击的 asp.net 事件处理程序被调用两次

问题描述

我在 asp.net mvc 核心项目中有一个包含一些列的表。

我的视图文件看起来像这样

    <h1>Items</h1>
<div class="panel-body">
    <table class="table table-bordered table-responsive table-hover">
        <thead>
            <tr>
                <th>Id</th>
                <th>Title</th>

                <th>Rating</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.Items)
            {
                <tr onclick="location.href='@(Url.Action("ShowItemDetails", "Item", new {Id = item.FilmId}))'">
                    <td>@item.Id</td>
                    <td>@item.Title</td>

                    <td>@item.Rating</td>
                    <td>@Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id })  | @Html.ActionLink("Rate this", "RateItem", new { id = item.Id }) </td>

                </tr>
            }
        </tbody>
    </table>
</div>

问题是当我点击一行时,控制器方法 ShowItemDetails 被调用了两次(!)。我无法从上面的代码中看出为什么会发生这种情况。此外,单击 Edit 或 Rate 这将首先调用 ShowItemDetails,然后立即在控制器中调用 Edit 或 RateItem 方法。有什么建议可以解决这个问题吗?

标签: asp.netasp.net-mvcasp.net-core

解决方案


单击 Edit 或 Rate 这首先调用 ShowItemDetails ,然后立即调用 Edit 或 RateItem 方法,因为 Edit 在 tablerow 下和 tablerow 上,您调用了 showitemdetails action.so,当您单击 td 时,它首先执行 row action 然后 td action .这就是为什么它被调用两次。

我希望,您想使用表格数据显示详细信息和编辑选项,而 Edit 是控制器名称。

调整您的表格代码,如下所示:

<tbody>
@foreach (var item in Model.Items)
  {
    <tr>
        <td>@Html.ActionLink("Show Details","ShowItemDetails","Item",new {Id = item.FilmId})</td>
        <td>@item.Id</td>
        <td>@item.Title</td>    
        <td>@item.Rating</td>
        <td>@Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id })  | @Html.ActionLink("Rate this", "RateItem", new { id = item.Id }) </td>
    </tr>
  }
</tbody>

推荐阅读