Sunday, July 31, 2011

MVC Multiple Post buttons in one page

Anyone who has worked in MVC knows how clicking a post button will submit the page, and invoke the action method. It can get a bit annoying if you want to do different things based on different buttons being clicked. However, thanks to html there is a way around it.


To do this, we have to figure out which button was clicked. This can be done in the following way:

Make two buttons with the same “name” but different “value”
e.g

<input type="submit" id="GetResults" name="SubmitButton" value="Apply" />
<input type="submit" id="UpdateResults" name="SubmitButton" value="Inform" />

In the controller action, add the following input parameter (string SubmitButton)
Inside the controller action, the value of the variable “SubmitButton” will either be “Apply” or “Inform” depending upon which submit button was clicked.

After this, a simple “if” condition such as the one given below will do the job:

If(SubmitButton == "Apply")
{
                Do this
}
Else if (SubmitButton == "Inform")
{
                Do that
}

No comments:

Post a Comment