【发布时间】: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