我正在運行MVC3,.Net 4和VS2010。我有以下示例項目來說明問題。防僞令牌和Ajax JSON帖子不起作用
我的控制器代碼
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中包含令牌。
任何想法我的代碼有什麼問題?
@nemesv我看到這篇文章,我也問過那裏的問題,但沒有答案。 – hardywang
那麼這個答案對於你來說還不夠嗎? http://stackoverflow.com/a/7603172/538387 – Tohid