简体   繁体   English

在MVC5中使用AJAX调用

[英]Using AJAX call in MVC5

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 ie 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. 我曾尝试在MVC5项目中使用AJAX调用,就像网络上的许多类似示例一样,但是每次出现错误时,例如antiforgerytoken,500等。我正在寻找一种具有Controller Action方法且具有所有优点的正确AJAX调用方法。必要的属性,并将模型数据从View发送到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. 控制器:由于防伪令牌或类似问题,代码无法使用此Action方法。

[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. 我只需要适当的AJAX和Action方法即可用于MVC5中的CRUD操作。 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). 1)我们没有使用“ __RequestVerificationToken”,并且不确定是否将其正确发送到控制器(它似乎是Firebug的“请求标头”中的cookie,但我不确定是否可以)。 Any idea? 任何想法?

2) Should I use var formdata = new FormData($('#frmRegister').get(0)); 2)我应该使用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? 3)为什么在这种情况下我必须避免使用processData和contentType?

4) Is the Controller method and error part of the AJAX method are OK? 4)Controller方法和AJAX方法的错误部分是否可以使用? Or is there any missing or extra part there? 还是那里缺少或多余的部分?

If the model in your view is RegisterViewModel and you have generated the form controls correctly using the strongly typed HtmlHelper methods, then using either new FormData($('#frmRegister').get(0)) or $('#frmRegister').serialize() will correctly send the values of all form controls within the <form> tags, including the token, and it is not necessary to add the token again. 如果视图中的模型是RegisterViewModel并且已使用强类型化的HtmlHelper方法正确生成了表单控件,则使用new FormData($('#frmRegister').get(0))$('#frmRegister').serialize()将正确发送<form>标记内的所有表单控件的值,包括令牌,并且无需再次添加令牌。

If your form does not include a file input, then the code should be 如果您的表单不包含文件输入,则代码应为

$('form').submit(function (event) {
    event.preventDefault();
    var formData = $('#frmRegister').serialize();
    $.ajax({
        type: "POST",
        url: '@Url.Action("Insert", "Account")', // do not hard code your url's
        data: formData,
        datatype: "json", // refer notes below
        success: function (data) {
            $('#result').html(data);
        }
    });
});

or more simply 或更简单

$.post('@Url.Action("Insert", "Account")', $('#frmRegister').serialize(), function(data) {
    $('#result').html(data);
});

If you are uploading files, then you need you need to use FormData and the code needs to be (refer also this answer and 如果您要上传文件,则需要使用FormData ,并且代码必须是(另请参阅此答案

$('form').submit(function (event) {
    event.preventDefault();
    var formData = new FormData($('#frmRegister').get(0));
    $.ajax({
        type: "POST",
        url: '@Url.Action("Insert", "Account")',
        data: formData,
        processData: false,
        contentType: false,
        datatype: "json",  // refer notes below
        success: function (data) {
            $('#result').html(data);
        }
    });
});

Note that you must set both processData and contentType to false when using jQuery with FormData . 请注意,将jQuery与FormData一起使用时,必须将processDatacontentType都设置为false。

If you getting a 500(Internal Server Error) , it almost always means that your controller method is throwing an exception. 如果收到500(Internal Server Error) ,则几乎总是表示您的控制器方法抛出异常。 In your case, I suspect this is because your method is returning a partial view (as suggested by the $('#result').html(data); line of code in you success callback) but you have specified that the return type should be json (your use of the datatype: "json", option). 在您的情况下,我怀疑这是因为您的方法正在返回部分视图(如$('#result').html(data); success回调中的代码行所建议),但是您已指定返回类型应该为json (您使用的datatype: "json",选项)。 Note that it is not necessary to specify the dataType option (the .ajax() method will work it out if its not specified) 请注意,没有必要指定dataType选项(如果未指定.ajax()方法,它将起作用)

If that is not the cause of the 500(Internal Server Error) , then you need to debug your code to determine what is causing the expection. 如果这不是导致500(Internal Server Error) ,那么您需要调试代码以确定引起期望的原因。 You can use your browser developer tools to assist that process. 您可以使用浏览器开发人员工具来协助该过程。 Open the Network tab, run the function, (the name of the function will be highlighted), click on it, and then inspect the Response. 打开“网络”选项卡,运行该功能(该功能的名称将突出显示),单击它,然后检查“响应”。 It will include the details of the expection that was thrown. 它将包括抛出的期望的详细信息。

contentType should be application/x-www-form-urlencoded contentType应该为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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM