【问题标题】:Return JSON with ajax is giving me blank page with return parameters使用 ajax 返回 JSON 给了我带有返回参数的空白页
【发布时间】:2021-12-31 14:38:18
【问题描述】:

我像这周一样开始学习 AJAX,我试图在 asp mvc 的页面上做一个简单的投票 - 当你点击一个按钮时,你会收到一个弹出窗口(在浏览器中)的消息并计算增量,当你点击第二个时,你得到另一个计数减量,你明白了。 我想测试是否可以像投票系统(upvotes/downvotes)一样在点击时更新自身的oount,而无需刷新页面。 但是,当我单击此按钮时,它会显示返回 json 包含的内容的空白页面。 (图片包含在帖子的最底部)。 我很可能遗漏了一些明显的东西,所以请多多包涵,如果你能告诉我我哪里错了,请这样做。

我的控制器:

 public IActionResult Privacy()
        {
            Vote vote = new Vote();
            vote.Votes = 0;
            return View(vote);
        }

        


        [HttpPost]
        public ActionResult VoteUp(string plus, string minus)
        {
            Vote vote = new Vote();

            if (plus == null)
            {
               
                vote.Votes = vote.Votes -1;
                var message = "You voted down";
                return Json(new { success = true, message = message }, new Newtonsoft.Json.JsonSerializerSettings());
            }
            else if ((minus == null))
            {
                
                vote.Votes = vote.Votes +1 ;
                var messagez = "You voted up";
                return Json(new { success = true, message = messagez }, new Newtonsoft.Json.JsonSerializerSettings());
            }
            else { }
            var messagebad = "STH WENT WRONG";
            return Json(new { success = true, message = messagebad }, new Newtonsoft.Json.JsonSerializerSettings());
        }


我的观点:

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




<form  asp-action="VoteUp" asp-controller="Home" method="POST" data-ajax="true">


    <div class="form-group"> </div>



    <div class="input-group-button">
        <button name="plus" class="btn btn-dark" onclick="" value="1" >+</button>
        @Model.Votes

        <button name="minus" class="btn btn-dark" onclick="" value="-1" >-</button>

    </div>

</form>


    @section scripts{
        <script src="~/lib/ajax/jquery.unobtrusive-ajax.js"></script>
        <script src="~/lib/jquery/dist/jquery.js"></script>


        <script type="text/javascript">

                function SubmitForm(form) {
                    form.preventDefault();
                $.ajax({
                    type: "POST",
                    url: "HomeController/VoteUp",  //form.action,
                    data: ('#form'),
                    success: function (data) {
                        if (data.success) {
                            alert(data.message);
                        } else {

                        }
                    },

                });
                
               
              

            };


        </script>
    }

我的模特:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace JSON_RETURN.Models
{
    public class Vote
    {
        public int Votes { get; set; }
    }
}

我每次点击都会得到一个空白页面(消息各不相同): (https://imgur.com/uVNSmE6)

【问题讨论】:

    标签: c# ajax asp.net-mvc asp.net-core


    【解决方案1】:

    你所做的只是一个表单提交而不是使用 ajax。为什么它返回 json 字符串是因为您在后端代码中返回了 json 字符串(return Json(new { success = true, message = messagebad }, new Newtonsoft.Json.JsonSerializerSettings());)。

    我看到您在代码中使用了jquery.unobtrusive-ajax.js,还使用 ​​ajax 创建了一个 js 函数。实际上,您只需要选择两种方式之一即可实现您的要求。

    这里是jquery.unobtrusive-ajax.js的正确使用方法:

    注意:

    1.如果使用asp.net core,默认在_Layout.cshtml中包含jquery.js。因此,当您使用@section Scripts{} 时,无需再次添加jquery.js。如果你的_Layout.cshtml不包含jquery.js,你需要在jquery.unobtrusive-ajax.js之前加上这个js文件:

    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/lib/ajax/jquery.unobtrusive-ajax.js"></script>
    

    2.您需要特定的data-ajax-update 来告诉元素在哪里需要使用AJAX 结果进行更新。

    更多jquery.unobtrusive-ajax.js支持的数据属性可以参考here

    查看:

    @model Vote
    @addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
    @{
        ViewData["Title"] = "sssss";
    }
    <div id="result"> //add this div...
                                                                     //add this...
        <form asp-action="VoteUp" asp-controller="Home" method="POST" data-ajax-update="#result" data-ajax="true">
            <div class="form-group"> </div>
            <div class="input-group-button">
                <button name="plus" class="btn btn-dark" value="1">+</button>
                @Model.Votes
                <input hidden asp-for="Votes" />         //add this....
                <button name="minus" class="btn btn-dark" value="-1">-</button>
            </div>
        </form>
    </div>
    
    @section scripts{
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js" integrity="sha256-v2nySZafnswY87um3ymbg7p9f766IQspC5oqaqZVX2c=" crossorigin="anonymous"></script>
    
    }
    

    控制器:

    注意:你可以看到我在表单中为Votes添加了一个隐藏的输入,这是因为只有输入或选择类型的元素可以发布到后端。我想获得Votes 值的原因是因为您的代码总是为Vote 创建一个新实例,该值将始终以0 开头。

    public IActionResult Privacy()
    {
        Vote vote = new Vote();
        vote.Votes = 0;
        return View(vote);
    }
    [HttpPost]
    public ActionResult VoteUp(string plus, string minus)
    {
        Vote vote = new Vote();
        vote.Votes = int.Parse(Request.Form["Votes"]); 
        if (plus == null)
        {
    
            vote.Votes = vote.Votes - 1;
        }
        else if ((minus == null))
        {
    
            vote.Votes = vote.Votes + 1;
        }
        else { }
        return PartialView("Privacy", vote);
    }
    

    结果:

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      • 2015-07-01
      • 2021-08-30
      • 1970-01-01
      相关资源
      最近更新 更多