Search code examples
javascriptasp.net-mvchtml-helperhtml.beginform

What is the purpose of using return in onsubmit parameter in Html.BeginForm?


In an ASP.NET MVC razor view I am submitting a form on button click. If I indicate 'return' on onsubmit parameter it behaves different than If I do not indicate 'return'.

So If I parametrize BeginForm as below:

Html.BeginForm("", "", FormMethod.Post, new { id = "myForm", onsubmit = "return doAction();", @class = "well" })

it behaves different from below one:

Html.BeginForm("", "", FormMethod.Post, new { id = "myForm", onsubmit = "doAction();", @class = "well" })

so What is the purpose of using return or not using it?


Solution

  • onsubmit = "doAction();"
    
    doAction(){
       alert("Hello World!");
    }
    

    ^ What this would do is just execute your function, and since doAction() isn't stopping the event from doing the default process, the form will submit.


    onsubmit = "return doAction();"
    
    doAction(){
       alert("Hello World!");
       return false; // form will not submit
       // return true; // form will submit
    }
    

    ^ What this would do is execute your function and if your function returns a false boolean value, it would prevent the form from submitting.


    To see where they exactly differ, try onsubmit="doAction()" and a function that returns false;

    onsubmit = "doAction();"
    
    doAction(){
       alert("Hello World!");
       return false; // the form will still submit
    }
    

    The form will still submit because you didn't indicate the return keyword despite the function returning false. The return keyword will signal the form to check the value returned by the function first.