【发布时间】:2016-07-11 04:31:10
【问题描述】:
我有一个可以正常工作的 JQuery 函数,但是如果我在 Action Method 上启用 [AntiForgerToken],则 JQuery 函数无法访问 Action Method,在我启用 AntiForgeryToken 的位置上,我还有其他 sn-p:
@using (Html.BeginForm("InsertStudent","Students",FormMethod.Post, new { @id="myform"}))
{
@Html.AntiForgeryToken()
不管view里面的@Html.AntiForgeryToken()是否开启,JQuery函数都很好用,问题出在Action Method上……
为什么会这样?我错过了什么??我读过在 Post Action 方法上启用 [AntiForgeryToken] 对于安全性非常重要,所以我认为应用程序应该在 Action Method 和 View 的两个地方都启用它。
jQuery 函数:
function InsertShowStudents() {
var counter = 0;
$.ajax({
type:"post",
url: "/Students/InsertStudent/",
data: { Name: $("#Name").val(), LastName: $("#LastName").val(), Age: $("#Age").val() }
}).done(function (result) {
if (counter==0) {
GetStudents();
CounterStudents();
counter = 1;
}
else {
$("#tableJQuery").append("<tr>"+"<td>"+result.Name+"</td>"+"<td>"+result.LastName+"</td>"+"<td>"+result.Age+"</td>"+"</tr>")
}
//clear the form
$("#myform")[0].reset();
}).error(function () {
$("#divGetStudents").html("An error occurred")
})
}
动作方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult InsertStudent(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
//ModelState.Clear();
return RedirectToAction("InsertStudent");
}
return View(student);
}
表格的列:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
@* <td style="display:none" class="tdStudentID">@Html.DisplayFor(modelItem => item.StudentID)</td> *@
<td>
<img src="~/images/deleteIcon.png" width="20" height="20" class="imgJQuery" data-id="@item.StudentID" />
</td>
<td>
@Html.ActionLink("Details","Details", new { id=item.StudentID})
</td>
</tr>
}
【问题讨论】:
-
您没有在 ajax 数据中传递令牌的值。如果您只使用
data: $('#myform').serialize(),最简单,它将序列化包括令牌在内的所有表单控件。但是在你的 POST 方法中使用RedirectToAction()是没有意义的——ajax 调用永远不会重定向。 -
@StephenMuecke 它现在可以工作了 :),您是否要发布答案以便我可以给您指出,或者如果我这样做,您更喜欢吗?
-
给我 20 分钟,我会添加这个和另一个替代方案
-
类似方式:stackoverflow.com/questions/14473597/…。可以使用
var token = $('#myform input[name=__RequestVerificationToken]').val();获取验证令牌,并将其传递到序列化数据部分。 -
@StephenMuecke 好的,我会更改Action Method 并删除
RedirectToAction()然后,没想到ajax 永远不会重定向
标签: c# jquery asp.net-mvc razor data-annotations