我這周開始學習 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://www.uj5u.com/qianduan/363727.html
標籤:C# 阿贾克斯 asp.net-mvc asp.net核心
上一篇:ASP.NETMVCCore外鍵
