Visar inlägg med etikett AJAX. Visa alla inlägg
Visar inlägg med etikett AJAX. Visa alla inlägg

onsdag 7 augusti 2013

Post Antiforgerytoken manually

When you use the helper @Html.AntiForgeryToken() in a view this is the actual HTML result:
<input name="__RequestVerificationToken" type="hidden" 
value="{ long cryptic code }">
This input field is normally inside your <form>-element which means it will be attached to the request if you submit that form.
The problem occurs when this input field is outside of your form or if you are not submitting a form. Have no fear, there is a solution for this. The attribute [ValidateAntiForgeryToken] tells the server to look for a key with the name: "__RequestVerificationToken". Let's give the server what it wants!
First, get that value!
var antiforgeytoken = $('input[name=__RequestVerificationToken]').val();
Second, attach it to your AJAX-request (I use jQuery)
$.ajax({
  url: 'something/something',
  type: 'POST',
  contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // Default
  data: { 'somekey': 'someval', 
          '__RequestVerificationToken', antiforgeytoken }
});
Now your server is happy, and you are too!
Update:
The content type is important because of how the MVC Binder validates the request. If you want to use another content type this solution How can i supply an AntiForgeryToken when posting JSON data using $.ajax? proposes to separate the antiforgery token and the postdata in two different parameters.

onsdag 1 augusti 2012

No more postback

Tack vare tekniken AJAX behövs inte längre postbacks mellan server och klient. Som användare är det frustrerande att byta sidor på en hemsida. Användarupplevelsen bryts för en sekund eller två. Som användare drar man sig för att klicka på vissa länkar för man vet inte om man kommer bli slungad till en annan sida eller vad som kommer att hända.

Om man skulle tänka nytt:
Vore inte det bästa om man som användare kommer in på en hemsida och man stannar kvar på samma sida under hela besöket. Tänk dig om du går in i en butik. Då går du runt i en och samma butik hela tiden. Om du byter rum så är du fortfarande i samma butik. Så borde webb-upplevelsen också vara. Du ska vara kvar på samma ställe. En förebild för mig här är Chrome Web Store. Du har fortfarande möjlighet att bokmärka http-adressen, men användarupplevelsen bryts aldrig.