0

So I have a partialview and I have 2 forms inside it as below:

@using (Html.BeginForm("AddAlbum", "Admin", FormMethod.Post, htmlAttributes: new { id = "frmAlbumAdd", novalidate = "novalidate", autocomplete = "off" }))
{
    @Html.AntiForgeryToken()
    <!--some controls and submit button-->
}
.....
.....
@using (Html.BeginForm("UploadImages", "Admin", FormMethod.Post, htmlAttributes: new { id = "frmUploadImages", novalidate = "novalidate", autocomplete = "off", enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <!--some controls and submit button-->
}

and I am doing ajax post to the Admin controller as below:

[HttpPost]
[ValidateAntiForgeryToken]//This works well
public JsonResult AddAlbum(AlbumDataModel model)
{
    //perform some task and return result
}

[HttpPost]
[ValidateAntiForgeryToken]//This results in Error
public JsonResult UploadImages([Bind(Prefix = "UIAModel")] UploadImageAlbum model)
{
    //perform some task and return result
}

and the error I get on second form submission is "The required anti-forgery form field \"__RequestVerificationToken\" is not present."

According to this post in SO we can have antiforgerytokens for different forms individually. But am not sure why this turns out to be error.

I've also tried adding @Html.AntiForgeryToken() in the Layout where partialviews load and excluded it from forms and had below ajaxSetup to send AntiForgeryToken but even that didn't work.

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    var verificationToken = $("meta[name='__RequestVerificationToken']").attr('content');
    if (verificationToken) {
        jqXHR.setRequestHeader("X-Request-Verification-Token", verificationToken);
    }
});

How can I overcome this issue? What is actually happening here?


UPDATE:

I am using ajax to post the formdata to controller as below:

$.ajax({
      url: url,
      type: "POST",
      dataType: 'json',
      data: formData,
      processData: false,
      contentType: false,
      success: function (data) {

      }
});
Community
  • 1
  • 1
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
  • Can you add the javascript that creates the ajax requests? – Robbert Brussaard Nov 03 '15 at 18:46
  • @RobbertBrussaard.. Updated question. Please check and let me know... – Guruprasad J Rao Nov 03 '15 at 18:55
  • How are you generating the value of `formdata`? If you use `var formdata = new FormData($('#frmUploadImages').get(0));` then everything including the token is serialized and you do not need you `$.ajaxPrefilter()` function (refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) for more detail) –  Nov 04 '15 at 01:00
  • And have you checked what `var verificationToken = $("meta[name='__RequestVerificationToken']").attr('content');` actually returns? - I suspect its `undefined`. –  Nov 04 '15 at 01:01
  • @StephenMuecke Its working fine.. haven't tried with `formdata` even though was aware of to use `formdata` while posting the `image`.. Can you please post it as answer? – Guruprasad J Rao Nov 04 '15 at 17:50
  • @StephenMuecke Could you please post an answer to this.. :) – Guruprasad J Rao Nov 09 '15 at 11:43
  • 1
    Hmm, must of missed your previous message. Need some sleep, but will do so in the morning :) –  Nov 09 '15 at 11:45
  • Sure buddy.. No probs.. :) – Guruprasad J Rao Nov 09 '15 at 11:48

2 Answers2

1

@Html.AntiForgeryToken() generates a hidden input with name="__RequestVerificationToken" so to get the value you need (for the first form)

var verificationToken = $('#frmAlbumAdd [name=__RequestVerificationToken]').val();

and then you can append it to the FormData object using

formData.append('__RequestVerificationToken', verificationToken);

However, since you are using FormData, you can simply serialize all the form controls, including the token and file inputs using

var formdata = new FormData($('#frmAlbumAdd').get(0));

Refer this answer for more details

Community
  • 1
  • 1
0

Can i suggest that you try the following:

$("form").on("submit", function (event) {
        event.preventDefault();
        var form = $(this);
        $.ajax({
            url: form.attr('action'),
            type: "POST",
            data: form.serialize(),
            success: function (data) {
               //your implementation
            },
            error: function (jqXhr, textStatus, errorThrown) {
                alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
            },
            complete: function () {
               //your implementation
            }
        });
    });

This does not uses json as the datatype. Do you really need to use json i like you to take a look at this How can i supply an AntiForgeryToken when posting JSON data using $.ajax?

Community
  • 1
  • 1
  • As of my knowledge, `dataType` is to basically consider what type of data we receive from server. But this issue is on sending part. I hope it will not effect much. Still let me give a try and let you know.. – Guruprasad J Rao Nov 04 '15 at 03:34