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.

edit

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教程

代码区博客精选文章
分页:12
转载请注明
本文标题:Translate the Ajax&amp;period;ActionLink MVC method to jQuery &amp;period;po ...
本站链接:https://www.codesec.net/view/611408.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(49)