我有一个将数据发送到控制器的ajax请求,它收集我的下拉菜单的值
错误是
POST http://localhost:65070/form/create 500 (Internal Server Error)
错误的回应是
The required anti-forgery form field "__RequestVerificationToken" is not present.
更新 我的表格
@using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>Form</legend> <div class="editor-label"> @Html.LabelFor(model => model.FormName) </div> <div class="editor-field"> @Html.EditorFor(model => model.FormName) @Html.ValidationMessageFor(model => model.FormName) </div> <div class="editor-label"> @Html.LabelFor(model => model.MasterID, "MasterModule") </div> <div class="editor-field"> @Html.DropDownList("MasterID", String.Empty) @Html.ValidationMessageFor(model => model.MasterID) </div> <select id="State" name="state"></select><br /> <p> <input type="submit" value="Create" /> </p> </fieldset> }
我的ajax请求
$('#State').change(function () { var a = $('#State').val(); $.ajax({ url: "/form/create", type: "POST", data: { 'SubID': a }, success: function (result) { // console.log(result); } }); });
我的控制器
public ActionResult Create(Form form, int SubID) { if (ModelState.IsValid) { form.SubId =SubID; form.CreatedDate = DateTime.Now; form.CreatedBy = 1; form.CreatedDate = DateTime.Now; form.IsActive = true; form.ModifyBy = 1; form.ModifyDate = DateTime.Now; db.Forms.Add(form); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.MasterID = new SelectList(db.Departments, "MasterId", "ModuleName", form.MasterID); return View(form); }
它给500内部错误..其笨拙的帮助
您的post方法必须具有[ValidateAntiForgeryToken]属性。删除属性或在视图中添加令牌
[ValidateAntiForgeryToken]
@Html.AntiForgeryToken()
并将其传递回ajax函数
$('#State').change(function () { var a = $('#State').val(); var token = $('[name=__RequestVerificationToken]').val(); $.ajax({ .... data: { __RequestVerificationToken: token, 'SubID': a }, ....
请注意,该form参数在操作方法中不是必需的
form
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(int SubID) { ....