Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

ASP.NET MVC: Multiple submit buttons using Ajax.BeginForm

Writer Emily Wong

I want to create a page that has a next button and previous button that switches the image displayed.

For that purpose I created an Ajax.BeginForm and inserted into it, an image and two submit buttons.

Can I (should I) have multiple submit buttons inside an Ajax.BeginForm?

How would the controller handle each submit separately?

3 Answers

Try this,

View

@model TwoModelInSinglePageModel.RegisterModel
@using (Ajax.BeginForm("DYmanicControllerPage", "Test", FormMethod.Post,null, new { id = "frmSignUp" }))
{ <div> <input type="hidden" name="hidden2" /> @Html.HiddenFor(m => m.hidden1) @Html.LabelFor(m => m.Name) @Html.TextBoxFor(m => m.Name) @Html.ValidationMessageFor(m => m.Name) </div> <br /> <div> @Html.LabelFor(m => m.Address) @Html.TextBoxFor(m => m.Address) @Html.ValidationMessageFor(m => m.Address) </div> <br /> <div> @Html.LabelFor(m => m.PhoneNo) @Html.TextBoxFor(m => m.PhoneNo) @Html.ValidationMessageFor(m => m.PhoneNo) </div> <input type="submit" value="Save" name="ButtonType"/> <input type="submit" value="Next" name="ButtonType" />
}

Controller

 [HttpPost] public ActionResult DYmanicControllerPage(RegisterModel model, string ButtonType) { if(ButtonType == "Next") { // Do Next Here } if (ButtonType == "Save") { //Do save here } return JavaScript("REturn anything()"); }
7

I would recommend that you have two buttons and then depending on what button was clicked you could set the action on the form:

Razor

$(function (){ $("#btn-prev").click(function() { $("#form").attr ( "action", "@Url.Action("Action", "Controller", new {area="Area" })", ).submit(); }); $("#btn-next").click(function() { $("#form").attr ( "action", "@Url.Action("Action", "Controller", new {area="Area" })", ).submit(); });
});

I am using jQuery here to do this, but I think you can get the idea.

3

I had the same requirement/issue and tried both solutions here and they both work for me. I LIKE the idea of setting the action via jquery when clicking so I can keep my actions separate so they can be used by other views.

HOWEVER, I've found that when I do this while I debug, it posts TWICE and BOTH the OnSuccess and OnFailure are triggered. It only happens when debugging though. Keep this in mind when picking.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy