Is there some easy way to handle multiple submit buttons from the same form? Example:
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" value="Send" />
<input type="submit" value="Cancel" />
<% Html.EndForm(); %>
Any idea how to do this in ASP.NET Framework Beta? All examples I've googled for have single buttons in them.
Just written a post about that: Multiple submit buttons with ASP.NET MVC:
Basically, instead of using
ActionMethodSelectorAttribute
, I am usingActionNameSelectorAttribute
, which allows me to pretend the action name is whatever I want it to be. Fortunately,ActionNameSelectorAttribute
does not just make me specify action name, instead I can choose whether the current action matches request.So there is my class (btw I am not too fond of the name):
To use just define a form like this:
and controller with two methods
As you see, the attribute does not require you to specify anything at all. Also, name of the buttons are translated directly to the method names. Additionally (I haven’t tried that) these should work as normal actions as well, so you can post to any of them directly.
I would suggest interested parties have a look at Maarten Balliauw's solution. I think it is very elegant.
In case the link dissapears, it's using the
MultiButton
attribute applied to a controller action to indicate which button click that action should relate to.This is the technique I'd use and I don't see it here yet. The link (posted by Saajid Ismail ) that inspires this solution is http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx). It adapts Dylan Beattie's answer to do localization without any problems.
In the View:
In the Controller:
Here is a mostly clean attribute-based solution to the multiple submit button issue based heavily on the post and comments from Maartin Balliauw.
razor:
and controller:
Update: Razor pages looks to provide the same functionality out of the box. For new development, it may be preferable.
Give your submit buttons a name, and then inspect the submitted value in your controller method:
posting to
EDIT:
To extend this approach to work with localized sites, isolate your messages somewhere else (e.g. compiling a resource file to a strongly-typed resource class)
Then modify the code so it works like:
and your controller should look like this:
I've came across this 'problem' as well but found a rather logical solution by adding the
name
attribute. I couldn't recall having this problem in other languages.http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
Meaning the following code
value
attributes can be changed, localized, internationalized without the need for extra code checking strongly-typed resources files or constants.On the receiving end you would only need to check if any of your known submit types isn't
null