You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC使用AJAX实现投票功能点击后返回JSON跳转空白页问题

问题原因汇总

  • 脚本加载顺序错误:jquery.unobtrusive-ajax.js 依赖jQuery,必须先加载jQuery再加载AJAX相关脚本
  • 自定义的SubmitForm函数未绑定到表单提交事件,点击按钮后触发了表单默认同步提交,直接跳转展示返回的JSON内容
  • AJAX请求参数错误:路由地址写法错误、表单选择器无效、未正确序列化表单数据
  • 后端逻辑问题:每次请求都新建Vote对象,票数未持久化,且返回结果未携带最新票数,前端无法更新页面显示

修正后的代码

1. View代码

@model JSON_RETURN.Models.Vote
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    ViewData["Title"] = "sssss";
}

<form id="voteForm" asp-action="VoteUp" asp-controller="Home" method="POST">
    <div class="input-group-button">
        <button name="plus" class="btn btn-dark" value="1">+</button>
        <span id="voteCount">@Model.Votes</span>
        <button name="minus" class="btn btn-dark" value="-1">-</button>
    </div>
</form>

@section scripts{
    <!-- 调整顺序,先加载jQuery -->
    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/lib/ajax/jquery.unobtrusive-ajax.js"></script>

    <script type="text/javascript">
        // 监听表单提交事件,拦截默认提交行为
        $('#voteForm').submit(function(e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "/Home/VoteUp",
                data: $(this).serialize(),
                success: function (data) {
                    if (data.success) {
                        alert(data.message);
                        // 更新页面显示的票数
                        $('#voteCount').text(data.votes);
                    }
                }
            });
        });
    </script>
}

2. Controller代码

public IActionResult Privacy()
{
    // 测试用将票数存在Session,生产环境可替换为数据库存储
    if (HttpContext.Session.GetInt32("VoteCount") == null)
    {
        HttpContext.Session.SetInt32("VoteCount", 0);
    }
    Vote vote = new Vote();
    vote.Votes = HttpContext.Session.GetInt32("VoteCount").Value;
    return View(vote);
}

[HttpPost]
public ActionResult VoteUp(string plus, string minus)
{
    int currentVotes = HttpContext.Session.GetInt32("VoteCount") ?? 0;
    string message;
    if (!string.IsNullOrEmpty(plus))
    {
        currentVotes += 1;
        message = "You voted up";
    }
    else if (!string.IsNullOrEmpty(minus))
    {
        currentVotes -= 1;
        message = "You voted down";
    }
    else
    {
        message = "STH WENT WRONG";
    }
    // 保存更新后的票数
    HttpContext.Session.SetInt32("VoteCount", currentVotes);
    // 返回结果携带最新票数供前端更新
    return Json(new { success = true, message = message, votes = currentVotes }, new Newtonsoft.Json.JsonSerializerSettings());
}

3. 额外配置(启用Session,.NET 6+版本)

需要在Program.cs中添加Session配置:

// 服务注册部分添加
builder.Services.AddSession();

// 中间件配置部分添加,注意要放在UseRouting之后、UseAuthorization之前
app.UseSession();

内容的提问来源于stack exchange,提问作者bewilderBB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:45:03