jQuery Ajax calls and the Html.AntiForgeryToken()

前端 未结 20 2631
鱼传尺愫
鱼传尺愫 2020-11-22 16:34

I have implemented in my app the mitigation to CSRF attacks following the informations that I have read on some blog post around the internet. In particular these post have

20条回答
  •  星月不相逢
    2020-11-22 17:20

    Further to my comment against @JBall's answer that helped me along the way, this is the final answer that works for me. I'm using MVC and Razor and I'm submitting a form using jQuery AJAX so I can update a partial view with some new results and I didn't want to do a complete postback (and page flicker).

    Add the @Html.AntiForgeryToken() inside the form as usual.

    My AJAX submission button code (i.e. an onclick event) is:

    //User clicks the SUBMIT button
    $("#btnSubmit").click(function (event) {
    
    //prevent this button submitting the form as we will do that via AJAX
    event.preventDefault();
    
    //Validate the form first
    if (!$('#searchForm').validate().form()) {
        alert("Please correct the errors");
        return false;
    }
    
    //Get the entire form's data - including the antiforgerytoken
    var allFormData = $("#searchForm").serialize();
    
    // The actual POST can now take place with a validated form
    $.ajax({
        type: "POST",
        async: false,
        url: "/Home/SearchAjax",
        data: allFormData,
        dataType: "html",
        success: function (data) {
            $('#gridView').html(data);
            $('#TestGrid').jqGrid('setGridParam', { url: '@Url.Action("GetDetails", "Home", Model)', datatype: "json", page: 1 }).trigger('reloadGrid');
        }
    });
    

    I've left the "success" action in as it shows how the partial view is being updated that contains an MvcJqGrid and how it's being refreshed (very powerful jqGrid grid and this is a brilliant MVC wrapper for it).

    My controller method looks like this:

        //Ajax SUBMIT method
        [ValidateAntiForgeryToken]
        public ActionResult SearchAjax(EstateOutlet_D model) 
        {
            return View("_Grid", model);
        }
    

    I have to admit to not being a fan of POSTing an entire form's data as a Model but if you need to do it then this is one way that works. MVC just makes the data binding too easy so rather than subitting 16 individual values (or a weakly-typed FormCollection) this is OK, I guess. If you know better please let me know as I want to produce robust MVC C# code.

提交回复
热议问题