ASP.NET核心AJAX帖子



我写了这个ASP.NET核心代码,但我遇到了这个错误"未捕获的语法错误:无效或意外的标记";。在StartUp中,我添加了HeaderName=X-CSRF-TOKEN的Antiforgery。

@model FinanceWorld.Web.ViewModels.Analyzes.AllAnalyzesViewModel
@{
this.ViewData["Title"] = "Analyzes";
}
<h1 class="text-center">@this.ViewData["Title"]</h1>
<hr />
<div class="row">
@foreach (var analyze in Model.Analyzes)
{
<div class="card col-md-3 mb-3" style="width: 18rem;">
<img src="@analyze.Image" class="card-img-top pt-3" alt="@analyze.Title">
<div class="card-body">
<h5 class="card-title">@analyze.Title</h5>
<p class="card-text">@analyze.Description</p>
<p class="card-text">@analyze.AddedByUserUserName</p>
</div>
<div>
<form method="post" id="votesForm"></form>
<ul class="list-unstyled d-flex justify-content-around">
<li class="d-inline" style="font-size: 35px" onclick="sendVote(@analyze.Id, 
true)">
<i class="far fa-thumbs-up"></i>
</li>
<li class="d-inline" style="font-size: 35px" onclick="sendVote(@analyze.Id, 
false)">
<i class="far fa-thumbs-down"></i>
</li>
</ul>
</div>
</div>
}
</div>
@section Scripts {
<script>
function sendVote(analyzeId, isUpVote) {
var token = $('#votesForm input[name=__RequestVerificationToken]').val();
var json = { analyzeId, isUpVote };
$.ajax({
url: "/api/votes",
type: "Post",
data: JSON.stringify(json),
contentType: "application/json; charset=utf8",
dataType: "json",
headers: { 'X-CSRF-TOKEN': token },
success: function (data) {
$("#votesCount").html(data.votesCount);
}
});
}
</script>
}
namespace FinanceWorld.Web.Controllers
{
using System.Security.Claims;
using System.Threading.Tasks;
using FinanceWorld.Services.Data.Votes;
using FinanceWorld.Web.ViewModels.Votes;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class VotesController : ControllerBase
{
private readonly IVotesService votesService;
public VotesController(IVotesService votesService)
{
this.votesService = votesService;
}
[HttpPost]
[Authorize]
public async Task<ActionResult<PostVoteViewModel>> Vote(VoteInputModel model)
{
string userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;
await this.votesService.SetVote(model.AnalyzeId, userId, model.IsUpVote);
var votes = this.votesService.GetVotes(model.AnalyzeId);
return new PostVoteViewModel { VotesCount = votes };
}
}
}
namespace FinanceWorld.Web.ViewModels.Votes
{
public class VoteInputModel
{
public string AnalyzeId { get; set; }
public bool IsUpVote { get; set; }
}
}

我根本没有在函数sendVote(analyzeId,isUpVote(中输入,我希望这段代码会有用,之后我将在View中实现votesCount。如果可能的话,请帮帮我。我会很感激的。

尝试此代码

var data = { AnalyzeId: analyzeId, IsUpVote: isUpVote };
$.ajax({
type: "POST",
url: "/api/votes",
data: data,
headers: { 'X-CSRF-TOKEN': token },
success: function (data) {
$("#votesCount").html(data.votesCount);
}
});

控制器内

[Route("api/votes/vote")]
public async Task<ActionResult<PostVoteViewModel>> Vote(VoteInputModel model)

在Ajax 中

url: "/api/votes/vote",

最新更新