user818700
user818700

Reputation:

ASP.Net MVC 4 Set 'onsubmit' on form submission

I have the following form:

@Html.BeginForm("ActionMethod","Controller",FormMethod.Post)

On submission I want to run a Javascript function, so I added the following:

@Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "myJsFunction()" })

But, it doesn't work... What am I doing wrong? Thanks!

Upvotes: 9

Views: 33861

Answers (2)

Md Shahriar
Md Shahriar

Reputation: 2736

@using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "form1Demo", onsubmit = "return CheckSubmit(event);" })){

//form

}

<script>

    function CheckSubmit(e) {

        var Name = $("#Name").val();

        var Roll = $("#Roll").val();

        var Price = $("#Price").val();

        if (Name == "" || Roll == "" || Price == "") {

            $("#msg").html("Please Enter All Values!");

            swal("Validation Error!", "Please Insert All Values", "warning");

            return false;
        }

        return true;
    }

</script>

Upvotes: 0

hutchonoid
hutchonoid

Reputation: 33306

You need this instead:

@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "return myJsFunction()" }))
{
        //form
}

Notice the using this makes the form self closing, without the using you need to close it as detailed in this MSDN article.

You can confirm javascript is called with this to isolate the problem:

@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { onsubmit = "alert('test')" }))
{
        <input type="submit" value="test" />
}

This should pop up an alert.

If the first one fails and the second one works, there is a problem with your js script references. This would raise an error in your browser console.

Update

Instead of binding your form obtrusively, if you give your form an Id you could use the following jquery instead (jQuery reference):

@using (Html.BeginForm("ActionMethod","Controller",FormMethod.Post, new { id = "target"}))
{
        //form
}

<script>
    $(function () {
        $("#target").submit(function (event) {
            event.preventDefault();
            myJsFunction();
        });
    });
</script>

This would bind when the form when the document is ready.

Upvotes: 17

Related Questions