Frage

I have a number of index pages where the row has an actionlink like so

@Ajax.ActionLink("Delete", "Delete", "AdverseEvent", new { id = Model.AdverseEventId }, new AjaxOptions { HttpMethod = "Post",OnSuccess = "rowDeleted", LoadingElementId="ajaxRequest_processing", Confirm = String.Format("Are you sure you want to delete adverse event for participant {0} at {1} ?", Model.ParticipantId, Model.EventTime) }, new { @class = "deleteAction" })

An actionlink is a great way to use progressive enhancement, because of course there is also a delete action, with get and post methods to perform the delete for those with javascript disabled.

I need to add an AntiForgeryToken. For an Ajax.BeginForm helper, Jon White's code works beautifully:

$.ajaxPrefilter(function (options, localOptions, jqXHR) {
    var type = options.type.toLowerCase();
    if (type === 'post') {
        var token = GetAntiForgeryToken();
        jqXHR.setRequestHeader(token.name, token.value);
    }
});

When this gets executed within an actionlink, I assume because the index table is not wrapped in a form, I get the error message:

The required anti-forgery form field "__RequestVerificationToken" is not present

So i could wrap the whole table in a form posting back to the delete action, but this is then not very neat if I want to use other ajax.actionlinks to different actions within the table. I could wrap each actionlink in its own form, each with its own antiforgery token, but this is a significant amount of extra markup, and will leave dozens of elements on the page with identical values and name. The other option would be to use the ActionLink OnBegin method to wrap the button in a form, but the unobtrusive ajax library does not seem to pass any reference to the element causing the ajax get/post (foolishly in my opinion - you can upvote this issue on codeplex).

Any thoughts on a neat solution? Thank you.

War es hilfreich?

Lösung

You can add the token into the page and then use Ajax to send the field over in another call.

see How to include the @Html.AntiForgeryToken() when deleting an object using a Delete link

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top