Yanayaya
Yanayaya

Reputation: 2184

Is it possible to have more than one submit button in an MVC Ajax form and pass a parameter?

Is it possible to have more than one submit button for an ajax form in MVC? I have a form that I'd like to have more than one submit button and have the outcome of the clicked button governed by a conditional statement in the controller.

Please consider the following Ajax code which I have in my application. It's an ajax form that calls the Create method of the Car controller when it's submitted.

@using (Ajax.BeginForm("Create", "Car", new AjaxOptions {
    HttpMethod = "POST",
    OnSuccess = "NotifySuccess",
    OnFailure = "NotifyFailure" }))
{
    ..form code

    <button type="submit" data-option="no_add">Save &amp; Close</button>
    <button type="submit" data-option="yes_add">Save &amp; Add</button>
}

As you can see I have already put in two submit buttons, my plan was that using data attributes I could potentially have a condition in the controller to define an outcome.

For example, if you click on Save & Close you'll simply be taken back to the index page if you click on Save & Add you'll be taken to another form potentially with an option parameter defined. Here is a quick snapshot of my create method in my controller.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Car car, string something)
{
    if(something = "whatever")
        try
            {
                if (ModelState.IsValid)
                {
                    unitOfWork.CarRepository.Insert(car);
                    unitOfWork.Save(); 
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
              ...handle catch
            }
        return View(car);
    else {
        ...do something else
    }
}  

The issue I have is that any input of type submit just submits the form. Is it possible to have more than one submit and control them at controller level based on say a parameter?

Upvotes: 0

Views: 60

Answers (1)

Brian Mains
Brian Mains

Reputation: 50728

I do the following in my forms:

<button type="submit" name="Action" value="SAVE" ..
<button type="submit" name="Action" value="DELETE" ..

And in my controller:

public ActionResult Edit(string Action, MyViewModel model)

When a button is clicked, only that button (when a submit button) posts back a value via the "Action" input field. So clicking the save button posts "SAVE", etc. So you can use that parameter to determine what action was triggered. It can be a prop on your model, or it can be how it appears above.

I don't use the AJAX form but it should work similarly.

Upvotes: 1

Related Questions