Massey
Massey

Reputation: 1125

How to prevent postback in beginform asp.net mvc

In my view I have a beginform, which has two buttons, one for save and one for cancel. When save is clicked, it validates the data in the form controls both client side and server side and postback to the controller. The problem is when I click either Save or Cancel, it tries to validate the data and shows validation summary. However I want to prevent postback and validation when the cancel button is clicked. In the cancel button I am calling a javascript function named Cancel() which calls window.history.back(-1); Still it is trying to postback. The following is my code. If I move the cancel button out of the form, then it doesn't do postback, but then styling is messed up as I want both the save and cancel button side by side

 <div id="updateusercreds" class="items">
                    @using (Html.BeginForm("SaveCustomer", "NewCustomer"))
                    {
                     <div>
                        @Html.LabelFor(x => x.Address.Email)
                        <span>
                            @Html.Kendo().TextBoxFor(model => model.Address.Email)
                        </span>
                    </div>
                    <div>
                    @Html.LabelFor(x => x.Address.Company)
                    <span>
                        @Html.Kendo().TextBoxFor(model => model.Address.Company)
                    </span>
                    </div>

                    <div>
                        @Html.LabelFor(x => x.Address.StreetAddress1, "Street Address")
                        <span>
                            @Html.Kendo().TextBoxFor(model => model.Address.StreetAddress1)
                            <br/>
                            @Html.Kendo().TextBoxFor(model => model.Address.StreetAddress2)
                        </span>
                    </div>

                    <div>
                    @Html.LabelFor(x => x.Address.Fax)
                    <span>
                        @Html.Kendo().TextBoxFor(model => model.Address.Fax)
                    </span>
                    </div>
                    @Html.ValidationSummary()
                    @Html.TradeUI().NotificationSummary()

                    <div class="tti-actions">
                        <button type="submit">Save</button> 
                        <button onclick="javascript:Cancel();">Cancel</button>                             
                    </div>
                    }

                </div>

Upvotes: 0

Views: 1714

Answers (1)

Pluc
Pluc

Reputation: 2929

Set the button type to button

<button type="button" onclick="javascript:Cancel();">Cancel</button>

Upvotes: 1

Related Questions