Dynamic Forms and AntiForgeryToken MVC

I want to create dynamic forms on an MVC page that will generate something like this.

onclick="
    var f = document.createElement('form'); 
    f.style.display = 'none'; 
    this.parentNode.appendChild(f); 
    f.method = 'POST'; 
    f.action = this.href;
    var s = document.createElement('input'); 
    s.setAttribute('type', 'hidden');
    s.setAttribute('name', 'authenticity_token'); 
    s.setAttribute('value', '6I6td2wJRI9Nu5Au/F3EfOQhxJbEMXabuVXM0nXonkY=');
    f.appendChild(s);
    f.submit();
    return false;"

      

I'm just not sure how I can implement the AntiForgeryToken over something like the above?!? any help should be appreciated

+2


a source to share


1 answer


It seems that you are calling dynamic forms is actually an attempt to convert anchor links to forms so you can POST instead of GET. In this case, I would recommend that you generate the form directly on the server, instead of worrying about publishing a link, which you would later turn into a form using all this javascript in an event onclick

:

So instead of:

<%= Html.ActionLink("OK", "controller", "action", null, 
    new { onclick = "Some ugly javascript" })%>

      



you can directly:

<% using (Html.BeginForm("controller", "action")) { %>
    <%= Html.AntiForgeryToken() %>
    <input type="submit" value="OK" />
<% } %>

      

+2


a source







All Articles