在MVC5中处理AJAX请求时出现内部服务器错误

时间:2014-10-10 11:27:49

标签: jquery ajax asp.net-mvc

我有一个MVC 5应用程序,在我的_Layout.cshtml文件中,我有这样的东西:

<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 localhost:44300 / Home / ServiceRequest [HTTP / 1.1 500 Internal Server   错误4ms]

知道问题可能是什么?以及如何解决?

1 个答案:

答案 0 :(得分:2)

您的操作方法具有ValidateAntiForgeryToken属性,但AJAX调用未传递令牌。删除属性,它将起作用。

或者,您需要在AJAX POST中包含防伪令牌,方法是在页面上放置@Html.AntiForgeryToken(),然后将此值放入隐藏的输入中。