Tuesday, April 5, 2011

How do I submit a form with a link in ASP.Net MVC?

I have a HTML form, and I have a Controller Action that accepts the POST request. Everything works with a regular submit button, but I would like to submit the form with a link (<a>-tag) instead, to be able to further control the formatting. Is there any way of doing this nicely built into the ASP.NET MVC Framework, or should I write my own extension method? Is it even possible to do this without javascript (I will use AJAX in the future, but it has to work without).

From stackoverflow
  • You should simulate something like __doPostBack in Web forms in Javascript like this:

    <form method="POST" action="URL" id="myForm">
       <input type="hidden" id="myInput" />
    </form>
    <script type="text/javascript">
       function postback(data) {
           document.getElementById("myInput").value = data;
           document.getElementById("myForm").submit();
       }
    </script>
    

    And then define the link as:

    <a href="javascript:postback('some data')">click here</a>
    
    Tomas Lycken : this does solve the problem for js-enabled browsers. what happens to the ones that do not have js enabled? i suppose i could use a
    Mehrdad Afshari : There is no way you could submit a form with an tag without JS. MS itself, uses this solution for Web forms.
  • I'm not aware of a helper and as far as I know it is impossible to submit a form using an anchor tag without using javascript.

  • Here is a complete example. Note that this particular example does something fairly important: it has a fallback for browsers with JavaScript disabled.

  • You cannot 'submit a form' using a link (<a> tag) without Javascript. The javascript is going to generate a standard POST request (same as clicking a submit form button) behind the scenes.

    There are other workarounds for those with JS disabled, look at what @Craig Stuntz submitted.

0 comments:

Post a Comment