2014-08-29 136 views
2

我有發送數據到我的控制器AJAX請求,它收集我的下拉的值POST 500(內部服務器錯誤)AJAX,MVC

誤差是錯誤的

POST http://localhost:65070/form/create 500 (Internal Server Error) 

響應是

The required anti-forgery form field "__RequestVerificationToken" is not present. 

UPDATE 我的形式

@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內部錯誤..其尷尬plz幫助

+0

這個錯誤的反應是什麼? – tymeJV 2014-08-29 18:49:33

+0

迴應?在沒有得到 – 2014-08-29 18:50:05

+0

Theres與錯誤的迴應...如500:沒有這樣的方法創建 - 沿着這些線的東西。在控制檯中打開「網絡」選項卡並觀看請求。 – tymeJV 2014-08-29 18:50:57

回答

8

您的帖子方法必須具有[ValidateAntiForgeryToken]屬性。或者刪除屬性或在視圖中,添加令牌

@Html.AntiForgeryToken() 

和其傳回在AJAX功能

$('#State').change(function() { 
    var a = $('#State').val(); 
    var token = $('[name=__RequestVerificationToken]').val(); 
    $.ajax({ 
    .... 
    data: { __RequestVerificationToken: token, 'SubID': a }, 
    .... 

注意form參數不處於行動方法必要

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create(int SubID) 
{ 
    .... 
+0

非常感謝!我一直堅持這個小時D: – Ross 2016-09-10 12:04:45

+0

這真的幫助。 :-) – user2695433 2017-09-22 10:04:30

相關問題