Search code examples
asp.net-mvchtml.beginformurl-action

submit form outside Html.BeginForm MVC


I want to be able to submit a form outside the Html.BeginForm, this is what i have and is working inside the form..

<button type="submit" class="btn btn-default" value="previous" formaction='@Url.Action("Previous", "StudentTest")' >previous </button>

I looked around and found a solution: give ur Html.BeginForm a name like this:

Html.BeginForm(new {name = "form1" })

and then use this :

onclick="document.form1.submit();"

But is it possible to use the same thing in the Url.Action instead of the onclick because i need the function in the controller?

Cheers


Solution

  • Try this:

    $('#sendButton').click(function(){
      $('form[name=yourFormName]').setAttrib('action','actionName');
      $('form[name=yourFormName]').submit();
    });
    

    Or try other way:

    $('#sendButton').on('click', function () {
                var yourData = { tag1 : $('#tag1').val(), tag2 : $('#tag2').val() /*etc..*/ };
                    $.ajax({
                        url: '@Url.Action("Action", "Controller")',
                        type: "POST",
                        data: yourData ,
                        success: function (response) {
                        //sended..
                        },
                        error: function (response) {
                        //not sended..
                        },
                    });
    });