我正在运行MVC3,.Net 4和VS2010。我有以下示例项目来说明问题。
我的控制器代码
namespace AntiForgeAjaxTest.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
MyData d = new MyData();
d.Age = 20;
d.Name = "Dummy";
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MyData data)
{
NameValueCollection nc = Request.Form;
return View(data);
}
protected override void ExecuteCore()
{
base.ExecuteCore();
}
}
}
我的观点和JavaScript代码
@model AntiForgeAjaxTest.Models.MyData
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
@using (Html.BeginForm("Index", "Index"))
{
@Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>@Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>@Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
alert(JSON.stringify(myObject));
$.ajax({
type: 'POST',
url: '/Index/Index',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(myObject),
success: function (result) {
alert(result);
},
error: function (request, error) {
alert(error);
}
});
});
});
</script>
</body>
</html>
这里我有2个按钮,第一个触发表单发布,第二个触发Ajax发布。表单帖子工作正常,但Ajax没有,服务器抱怨A required anti-forgery token was not supplied or was invalid.
,即使我已经在我的JSON中包含了令牌。
知道我的代码有什么问题吗?
答案 0 :(得分:1)
此代码有效。
@model AntiForgeAjaxTest.Models.MyData
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
@using (Html.BeginForm("Index", "Index"))
{
@Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>@Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>@Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
post();
});
});
function post() {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
$.post('/Index/Index/', myObject);
}
</script>
</body>
</html>