for循环中的ajax.beginform

时间:2010-09-29 04:36:23

标签: asp.net-mvc

所以我使用foreach循环迭代注释。评论部分包含在“评论”div中。删除注释并将其重新绑定到控件后,我的函数 DeleteComment 会再次获取注释。但是,删除评论后,无论何时尝试删除其他评论,第一个删除的评论的commentId将继续传递给 DeleteComment 函数,而不是传递您正在尝试的评论的commentId删除。如果刷新页面,则可以再次删除一条注释,如果尝试删除另一条注释则会出现同样的问题。

<table>
 <% foreach (var item in Model) { %>
<tr> <td>item.Comment </td>
    <td>
                    <%if (HttpContext.Current.User.Identity.IsAuthenticated && item.Poster.UserName == HttpContext.Current.User.Identity.Name)
                      { %>
                      <%using (Ajax.BeginForm("DeleteComment", "Home", new AjaxOptions {UpdateTargetId = "Comments"}))
                          {%>
                        <%=Html.Hidden("articleId", item.CarrierId) %>  
                        <%=Html.Hidden("num_comments", (int)ViewData["num_comments"]) %> 
                        <%=Html.Hidden("commentId", item.CommentId) %>
                        <input type = "submit" value = "delete" />
                        <%} %>
                    <%} %>
                </td>
</tr>
<table>

例如,您使用commentId 1删除评论...然后您尝试删除其他一些评论,但commentId 1会继续传递。你刷新页面,问题消失了......一个评论......

<div id = "Comments">
    <%if ((int)ViewData["num_comments"] > 0)
      { %>
    <%Html.RenderPartial("CommentsX", Model.Comments, new ViewDataDictionary{{"num_comments", ViewData["num_comments"] }}); %>
    <%} %>
    </div>

其中CommentsX是包含我在上面发布的for循环代码的ascx控件。

1 个答案:

答案 0 :(得分:0)

有时在同一页面上使用相同ID的多个元素可能会导致您看到的时髦结果。尝试使ID如下所示:

  <table>
 <% int index=1;
    foreach (var item in Model) { %>
<tr> <td>item.Comment </td>
    <td>
       <%if (HttpContext.Current.User.Identity.IsAuthenticated && item.Poster.UserName == HttpContext.Current.User.Identity.Name)
         { %>
            <%using (Ajax.BeginForm("DeleteComment", "Home", new AjaxOptions {UpdateTargetId = "Comments"}))
             {%>
                    <%=Html.Hidden("articleId" + index, item.CarrierId) %>  
                    <%=Html.Hidden("num_comments" + index, (int)ViewData["num_comments"]) %> 
                    <%=Html.Hidden("commentId" + index, item.CommentId) %>
                    <input type = "submit" value = "delete" />
            <%} %>
        <%    index++;
          } %>
    </td>
</tr>
<table>