weixin_33674976 2016-08-17 15:03 采纳率: 0%
浏览 69

在MVC5中使用AJAX调用

I have tried to use AJAX call in an MVC5 project as many similar examples on the web, but every time there is an error i.e. antiforgerytoken, 500, etc. I am looking at a proper AJAX call method with Controller Action method that has all the necessary properties and sending model data from View to Controller Action. Here are the methods I used:

View:

@using (Html.BeginForm("Insert", "Account", FormMethod.Post, new { id = "frmRegister" })) 
{
    @Html.AntiForgeryToken()
    //code omitted for brevity
}



<script>

    AddAntiForgeryToken = function (data) {
    data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
    return data;
    };

$('form').submit(function (event) {
        event.preventDefault();

        //var formdata = JSON.stringify(@Model); //NOT WORKING???
        var formdata = new FormData($('#frmRegister').get(0));
        //var token = $('[name=__RequestVerificationToken]').val(); //I also tried to use this instead of "AddAntiForgeryToken" method but I encounter another error

        $.ajax({
            type: "POST",
            url: "/Account/Insert",
            data: AddAntiForgeryToken({ model: formdata }),
            //data: { data: formdata, __RequestVerificationToken: token },
            //contentType: "application/json",
            processData: false,
            contentType: false,

            datatype: "json",
            success: function (data) {
                $('#result').html(data);
            }
        });

    });
</script>

Controller: Code cannot hit to this Action method due to antiforgerytoken or similar problem.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult Insert(RegisterViewModel model)
{
    try
    {
         //...
         //code omitted for brevity
    }
}

I just need a proper AJAX and Action methods that can be used for CRUD operations in MVC5. Any help would be appreciated.

UPDATE: Here is some points about which I need to be clarified:

1) We did not use "__RequestVerificationToken" and I am not sure if we send it to the Controller properly (it seems to be as cookie in the Request Headers of Firebug, but I am not sure if it is OK or not). Any idea?

2) Should I use var formdata = new FormData($('#frmRegister').get(0)); when I upload files?

3) Why do I have to avoid using processData and contentType in this scenario?

4) Is the Controller method and error part of the AJAX method are OK? Or is there any missing or extra part there?

  • 写回答

2条回答 默认 最新

  • ~Onlooker 2016-08-17 15:28
    关注

    contentType should be application/x-www-form-urlencoded

    Try this code

        <script>
    $('form').submit(function (event) {
            event.preventDefault();
    
        $.ajax({
            method: "POST",
            url: "/Account/Insert",
            data: $(this).serialize(),
           contentType:"application/x-www-form-urlencoded",
            success: function (data) {
           $('#result').html(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        });
    });
        </script>
    
    评论

报告相同问题?