【问题标题】:MVC multiple buttons with multiple sessions (ex: upvotes)具有多个会话的 MVC 多个按钮(例如:upvotes)
【发布时间】:2020-12-30 10:54:38
【问题描述】:

我正在尝试创建一个页面,您可以在其中为 MVC 5 中动态添加的帖子点赞,并计算每个帖子的点赞数。

 @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.ActionLink(item.Title, "Details", new { id = item.Id })
                </td>
                <td>
                    <img src="@item.ImgURL" style="max-width: 200px;" />
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Upvotes)
                    <button id="upvotes">Upvote</button>
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                    <button class="js-delete" data-model-id="@item.Id">Delete</button> |
                    @Html.ActionLink("Add to Hot Page", "AddToHot", new { id = item.Id })
                </td>
            </tr>
        }

赞成票显示在按钮前面,有没有办法使用会话将该按钮分配给赞成票数?

还有 p.s.有多个帖子都有自己特定的点赞数。

代码补充:

public ActionResult Upvote(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Meme meme = db.Memes.Find(id);
            if (meme == null)
            {
                return HttpNotFound();
            }
            meme.Upvotes++;
            db.Memes.Remove(db.Memes.Find(id));
            db.Memes.Add(meme);
            db.SaveChanges();
            return View(meme);
        }

P.S,我已将&lt;button id="upvotes"&gt;Upvote&lt;/button&gt; 更改为

@Html.ActionLink("Upvote", "Upvote", new { id = item.Id })

【问题讨论】:

    标签: c# asp.net-mvc session


    【解决方案1】:

    &lt;button id="upvotes"&gt;Upvote&lt;/button&gt; 在 for 循环中将呈现在 Id 属性中具有相同值的所有按钮。把它改成这样:

    <button id="upvotes@item.Id">Upvote</button>
    

    这将导致以下结果:

    <button id="upvotes1">Upvote</button>
    <button id="upvotes2">Upvote</button>
    <button id="upvotes3">Upvote</button>
    ...
    

    回到实际问题,您没有分享处理投票的操作的代码。该操作的返回类型是什么?

    我假设它是一个 ajax 动作和一个子动作,那么我猜你正在从该动作返回帖子的总投票数。

    在这种情况下,您可以将返回的数字(例如 15)附加到显示总数的容器中。

    【讨论】:

    • 如果这能解决您的问题,那就太好了。否则,请分享呈现页面的操作以及单击upvote 按钮时执行的操作。
    猜你喜欢
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    相关资源
    最近更新 更多