2014-10-10 39 views
0

AJAX請求我有一個MVC應用5,和我_Layout.cshtml文件裏面,我有這樣的事情:內部服務器錯誤,而處理MVC5

<div class="input-top"> 
     <a class="GoBtn" href=""><img src="~/Content/img/GOBtn.png" class="gobtn-position"></a> 
     <input id="homeZipCode" type="text" class="form-control input-position-2" placeholder="ZIP"> 
     <input id="homeService" type="text" class="form-control input-position-1" placeholder="What do you need done today?"> 
</div> 

而且一點是,當用戶填充上面的輸入並按下href屬性,我想打開一個新的視圖頁面並將數據發送到視圖。動作方法該視圖所屬的定義是這樣的:

[Authorize] 
public ActionResult ServiceRequest() { ... } 

[Authorize] 
[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult ServiceRequest(RequestViewModel rvm, HttpPostedFileBase image = null, HttpPostedFileBase video = null) { ... } 

我RVM視圖模型定義如下:

public class RequestViewModel 
{ 
    [Required(ErrorMessage = "Please select a state")] 
    [Display(Name = "State")] 
    public int StateID { get; set; } 

    [Required(ErrorMessage = "Please enter a zip code")] 
    [Display(Name = "Zip")] 
    public string ZipCode { get; set; } 

    [Required(ErrorMessage = "Please choose a service")] 
    [Display(Name = "Service")] 
    public string ServiceName { get; set; } 

    // more unrelated fields below 
} 

最後,我有我的AJAX調用,這是我的腳本之間定義我_Layout.cshtml文件內標籤:

<script> 

$(document).ready(function() { 
    $('a.GoBtn').on('click', function (e) { 

     e.preventDefault(); 

     debugger; 
     // Send an ajax post request with data 

     var homeZipCode = $("#homeZipCode").val(); 
     var homeService = $("#homeService").val(); 

     var model = { ZipCode: homeZipCode, ServiceName: homeService }; 

     $.ajax({ 
      url: '@Url.Action("ServiceRequest", "Home")', 
      contentType: 'application/json; charset=utf-8', 
      type: 'POST', 
      dataType: 'html', 
      data: JSON.stringify(model) 
     }) 
      .success(function (result) { 
      }); 
    }); 
}); 

</script> 

的問題是,當我填寫這兩個輸入框,然後按Go HREF,我得到一個錯誤消息說:

POST本地主機:44300 /首頁/ ServiceRequest [HTTP/1.1 500內部服務器錯誤 的4ms]

任何想法,問題可能是什麼?以及如何解決它?

+0

你試過'dataType:'JSON','? – christiandev 2014-10-10 11:29:44

+1

您是否附加了調試器或查看響應主體以查看錯誤的詳細信息? – Rhumborl 2014-10-10 11:30:02

+1

你填寫2個字段,但所有3個都是必需的,是這個問題嗎? – SSA 2014-10-10 11:30:17

回答

2

您的動作方法有ValidateAntiForgeryToken屬性,但AJAX調用不會傳遞令牌。刪除該屬性,它會工作。

或者,您需要在您的頁面上放置@Html.AntiForgeryToken(),然後將該值放入隱藏輸入中,以在AJAX POST中包含防僞標記。