2010-09-29 43 views
2

所以我使用foreach循环遍历评论。评论部分包裹在“评论”div中。我的功能DeleteComment在您删除评论并重新将其重新提交给控件后会再次提取评论。但是,删除评论后,只要您尝试删除其他评论,第一次删除评论的commentId就会继续传递给DeleteComment函数,而不是传递您要删除的评论的commentId。如果刷新页面,则可以再次删除一条评论,如果尝试删除另一条评论,则会出现同样的问题。ajax.beginform for循环

<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控件。

+0

你是如何“重新控制”?我看到“评论”的UpdateTargetId,但是我没有在您发布的代码中看到该元素。什么回来呢? – 2010-09-29 05:41:37

回答

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> 
+0

但问题是DeleteComment函数如何知道正确的索引?我的Ajax.BeginForm将数据提交给DeleteComment函数,该函数接受3个变量articleId,num_comments,commentId。 – TPR 2010-09-30 04:21:06