【发布时间】:2021-09-17 08:03:21
【问题描述】:
我编写了这个 ASP.NET Core 代码,但是我收到了这个错误“Uncaught SyntaxError: Invalid or unexpected token”。在 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 之后实现它。 请,如果可能的话,请帮助我。我将不胜感激。
【问题讨论】:
-
你能发布 /api/votes 控制器动作吗?
-
谢谢,也请提供 VoteInputModel 代码。