I’m wondering how you might go about implementing multiple form actions when submitting a form in asp.net mvc 3 RC.
If I’m editing a user, for example I would like to have an action bar with the following buttons;
“Save” | “Save and Close” | “Cancel”
Save – Submits the form and saves, returning you to the edit screen. Could be easily implemented as a standard input/submit button. Nothing special here.
Controller code for this might look like
public ActionResult Edit(UserViewModel model)
{
...
return RedirectToAction("Edit", model.Id");
}
Cancel – Just returns you to previous screen. I was thinking about using an anchor tag for this.
<a href="@Request.UrlReferrer" class="button">Cancel</a>
But I’m stumped on how to implement “Save and Close” when you need to submit the same form data. I was wondering about having a nullable close param maybe?
public ActionResult Edit(UserViewModel model, bool? close)
{
...
return close.GetValueOrDefault(false) ? RedirectToAction("Index", model.Id" : RedirectToAction("Edit", model.Id");
}
But how do I submit this extra param along with the form in this case?
If possible, I’d like to have a single form action for handling the submit as in the above mockup.
I’m also interested if anyone else has come up with a nice user interaction model around this idea.
Solution
I ended up using Omar’s suggestion below but instead of passing in a string I took in an enum so I don’t have to do string checks in all my controllers.
public ActionResult Edit(UserViewModel model, FormAction actionType)
{
// pre-check
if (actionType == FormAction.Cancel)
// just return user to previous view and don't save.
// Save code
if (actionType == FormAction.Save)
return ...
else if (actionType == FormAction.SaveAndClose)
....
}
Because I wanted a friendlier “Save and Close” text on the <input> button but wanted to use an enum I implemented a custom ModelBinder for FormAction that did the parsing.
I didn’t use a <button> tag because the theming was already in place for <input> tags.
You can have multiple submit buttons in a form with the same
nameattribute but differentvalueattributes. Which ever button is clicked, the associatedvaluewill be posted to the server.You can use a simple link for
Cancelbut I’ll include it as a button anyway.And in your action, test for the values.
If you don’t like having the long text in the
valueattribute, you can use standard HTML<button>tag which lets you define a separate value and separate text.