CD Smith
CD Smith

Reputation: 6607

How do I post back to an MVC controller action via Javascript

Currently I have a aspx page that is defined as:

    <%Using Html.BeginForm("SaveNotifications", "Notifications", FormMethod.Post, New With {.id = "NotificationForm"})%>
    ...
                    <tr>
                <td colspan="3">
                    <input type="submit" id="SaveNotifications" name="SaveNotifications" value="Save" class="t-button" />
                </td>
            </tr>
        </table>
        </fieldset> 
    <%End Using %>

I want to change this so that my input button fires a javascript function so that I can do some complex validation of the form and THEN post to the controller.

I changed my submit button to:

    <input type="submit" id="SaveNotifications" name="SaveNotifications" value="Save" class="t-button" onclick="onSave(); return false;" />

The onSave() method would fire but not post back to the controller.

The controller is defined as:

    <HttpPost()> _
    <MultiButton(MatchFormKey:="SaveNotifications", MatchFormValue:="Save")> _
    Function SaveNotifications(ByVal NotificationForm As FormCollection) As ActionResult
    ...
    End Function

How do I change this so that the javascript fires, runs my validation and then hits this controller action?

Thanks

Upvotes: 0

Views: 992

Answers (1)

Leniency
Leniency

Reputation: 5024

Change your submit button to

<input type="submit" id="SaveNotifications" name="SaveNotifications" value="Save" class="t-button" onclick="return onSave();" />

Then in the javascript onSave() function, return true or false depending on the validation.

function onSave()
{
    var isValid = true;
    // ... do your validation ...

    // ie:
    // if (field1.value.length == 0)
    //     isValid = false;


    // returning true will post the form.  False will halt it.
    return isValid;
}

Upvotes: 1

Related Questions