我正在尝试使用此代码发布 $.ajax 帖子:
$('button#removeTeamMember').click(function() {
var thisPlayerId = $(this).attr('data-bind').valueOf();
var thisTeamId = $('#hidden').text();
alert("PlayerId: " + thisPlayerId + " TeamId: " + thisTeamId);
$.ajax({
type: "POST",
url: "/Teams/RemoveTeamMember",
data: AddAntiForgeryToken({ playerId: thisPlayerId, teamId: thisTeamId }),
dataType: "text",
contentType: "application/json",
success: function(returnedData) {
if (returnedData.success === true) {
window.location = "/Teams/Details?id=" + thisTeamId;
} else {
alert("An error occurred removing the team member.");
}
},
error: function(jqxhr, textStatus, errorThrown) {
alert("jqxhr: " + jqxhr.readyState + "; " + jqxhr.status + "; " + jqxhr.responseText);
alert("textStatus: " + textStatus);
alert("errorThrown: " + errorThrown);
},
async: false
});
});
这是我的控制器代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RemoveTeamMember(int playerId, int teamId)
{
var teamMember = _teamMemberRepository.Query().FirstOrDefault(tm => tm.Player.PlayerId == playerId && tm.Team.TeamId == teamId);
_teamMemberRepository.Delete(teamMember);
//return RedirectToAction("Details");
return Json(new {success = true});
}
这是视图代码:
<form method="POST" action="#" role="form">
@Html.AntiForgeryToken()
<div class="panel panel-primary">
<div class="panel-heading"><h3>@Model.Team.TeamName</h3></div>
<div class="panel-body">
<div class="col-md-6">
<table class="table table-striped">
<thead>
<tr>
<th>Player Type</th>
<th>Player</th>
<th>Handicap</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Manager</td>
<td>@Html.ActionLink(@Model.Team.TeamManager.DisplayName, "#")</td>
<td></td>
<td></td>
</tr>
@foreach (var teamMember in @Model.Team.TeamMembers)
{
<tr>
<td>Player</td>
<td><a href="#">@teamMember.Player.DisplayName</a></td>
<td>Handicap</td>
<td>
<button id="removeTeamMember" class="btn btn-xs btn-danger" data-bind="@teamMember.Player.PlayerId">Remove</button>
<div id="hidden" style="visibility: hidden">@teamMember.Team.TeamId</div>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</form>
我收到错误消息,说 AntiForgeryToken 不存在,即使它是通过我从这里得到的“AddAntiForgeryToken”调用的。我还有什么做错的?