zoukankan      html  css  js  c++  java
  • jQuery Ajax calls and the Html.AntiForgeryToken()

    jQuery Ajax calls and the Html.AntiForgeryToken()

    https://stackoverflow.com/a/4074289/3782855

    I use a simple js function like this

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

    Since every form on a page will have the same value for the token, just put something like this in your top-most master page

    <%-- used for ajax in AddAntiForgeryToken() --%>
    <form id="__AjaxAntiForgeryForm" action="#" method="post"><%= Html.AntiForgeryToken()%></form>

    Then in your ajax call do (edited to match your second example)

    $.ajax({
        type: "post",
        dataType: "html",
        url: $(this).attr("rel"),
        data: AddAntiForgeryToken({ id: parseInt($(this).attr("title")) }),
        success: function (response) {
            // ....
        }
    });

    include antiforgerytoken in ajax post ASP.NET MVC

    You have incorrectly specified the contentType to application/json.

    Here's an example of how this might work.

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(string someValue)
        {
            return Json(new { someValue = someValue });
        }
    }

    View:

    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
    {
        @Html.AntiForgeryToken()
    }
    
    <div id="myDiv" data-url="@Url.Action("Index", "Home")">
        Click me to send an AJAX request to a controller action
        decorated with the [ValidateAntiForgeryToken] attribute
    </div>
    
    <script type="text/javascript">
        $('#myDiv').submit(function () {
            var form = $('#__AjaxAntiForgeryForm');
            var token = $('input[name="__RequestVerificationToken"]', form).val();
            $.ajax({
                url: $(this).data('url'),
                type: 'POST',
                data: { 
                    __RequestVerificationToken: token, 
                    someValue: 'some value' 
                },
                success: function (result) {
                    alert(result.someValue);
                }
            });
            return false;
        });
    </script
  • 相关阅读:
    php函数
    字符滚动效果0515复习笔记+注释
    0514复习Windows操作及DOM的使用
    超链接文字随状态改变变色2016-0514
    js笔记之影音插入0514
    js类型转换,运算符,语句
    JS学习1简介
    json文件的json.parse(data)方法时候碰到的问题
    样式属性
    css样式表0513补
  • 原文地址:https://www.cnblogs.com/chucklu/p/11532198.html
Copyright © 2011-2022 走看看