Alex Rivera | Logout

Asp.net mvc3 razor with multiple submit buttons

Asked 2011-04-18T12:03:12.310
32

I'm using MVC3 Razor. I have 2 submit buttons setup on my view but the problem I'm having is that both submit buttons cause the validation of the model. I want to hook up individual submit buttons with specific input controls for validation.

Edit
Report

1 Answer

30

The browser is always going to submit the entire form regardless of which submit button you press.

The best solution would be to have two submit buttons with the same value for the name attribute and different values for the value attributes.

When you submit the form, the value of the button will be submitted as well. In your action which handles that form submission, you check to see the value of the button and perform the correct validation based on that.

In your form you would have something like this:

<button type="submit" name="Command" value="command1">Do Command #1</button>
<button type="submit" name="Command" value="command2">Do Command #2</button>

Your Form Model would look like this:

public class MyFormModel() {
    public string Command {get;set;}
    public string SomeOtherVal {get;set;}
}

Your controller\action would look like this:

public ActionResult HandleFormSubmit(MyFormModel model) {
    if (model.Command == "command1") {
        // do something
    } else if (model.Command == "command2") {
        // do something else
    }
}
answered 2011-04-18T20:27:35.250

Your Answer