Search code examples
javascripthtmlhtml.beginform

use Html.BeginForm at runtime


i want to use Html.BeginForm conditionally. there are 2 fields inside code as below

@using (Html.BeginForm("Form1Action", "Form1", FormMethod.Post, new { id = "form1" }))
{

   <label for="firstlabel">Label 1</label>
      <input type="text" id="firstlabel" name="firstlabel"/>

   <label for="secondlabel">Label 2</label>
      <input type="text" id="secondlabel" name="secondlabel"/>
   <a href="#" class="button" onclick="SubmitForm();">Submit</a>
}

and JS is

<script type="text/javascript">
  function SubmitForm() {
    $('#form1').submit();
  }
</script>

if secondlabel is blank or empty then I want to submit the form by another action, so how can I make this happen?

by another action i mean :

 @using (Html.BeginForm("Form2Action", "Form2", FormMethod.Post, new { id = "form2" }))

Solution

  • Try this..

    function SubmitForm() {
    if($('#secondlabel').val().length)
        $('#form1').submit();
    else
     $('#form2').submit();
      }
    

    or by changing action

        function SubmitForm() {
        if($('#secondlabel').val().length == 0)
            $('#form1').attr('action', $('#form2').attr('action'));
    
    
      $('#form1').submit();
          }