I am dealing with this ASP.NET MVC problem of that using ValidateAntiForgeryToken with AJAX breaks the AJAX call (Using ValidateAntiForgeryToken with Ajax.ActionLink). The only solution (as stated in that topic) requires jQuery.

How do i do the eqvivalent of the following with jQuery's .post method?

@Ajax.ActionLink("Perform HTTPPost", "PostTest", new AjaxOptions{ HttpMethod="POST"})

Here is the Controller:

// [ValidateAntiForgeryToken] public class MoreInfoController : Controller { [HttpPost] public ActionResult PostTest() { return View(); } }

Here is it's Index VIEW with both javascript and HTML:

<script type="text/javascript"> $(document).ready(function () { $('#linkToPost').click(PostForm); }); function PostForm() { $.post("/PostTest", $('#testForm').serialize(), function(data) { }); return false; } </script> <a id="linkToPost" href="#">Perform HTTP Post</a> <form id="testForm" method="POST" > @Html.AntiForgeryToken() </form>

And here is the Route:

routes.MapRoute("PostTest1", "PostTest", new {controller = "MoreInfo", action = "PostTest"} );

My example is using $.ajax but you can easily change it to $.post

@Html.ActionLink("Perform HTTP Post", "PostTest", "Controller", null, new { id = "someId" }) <script type="text/javascript"> $(function() { $('#someId').click(function() { $.post({ url: $(this).attr('href'), type: 'post', success: function(data) { // assuming you're returning a partial result $('#somecontainer').html(data); } }); // prevent the default action return false; }); } </script>

If you don't want to give the anchor an id, you could use a class selector:

$('.ajax-link').click(function() { ... });

Instead of doing new { id = "someId" } you would need to do new { @class = "ajax-link" } or whatever you wanted your class to be named.


I was using the wrong overload. I was trying to set the id for the html attribute, not the route data.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

本文标题:Translate the Ajax&amp;period;ActionLink MVC method to jQuery &amp;period;po ...

技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(49)