Determining which submit button was used for a POST form in asp.net MVC
I have a view in asp.net MVC that has two submit buttons. I would like to know which button was clicked. The buttons work GREAT so there is no problem there, I just need to do a few different things depending on which button is. I checked the Request.Form [] collection and didn't add anything.
Here is my view code ....
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Data.TempPerson>" %>
<div class="phonePerson">
<% using (Ajax.BeginForm("Create", new AjaxOptions
{
UpdateTargetId = "divList",
HttpMethod = "Post",
OnSuccess = "RedoLayout"
}))
{ %>
<label for="Name">
Name:</label>
<%= Html.TextBox("Name")%>
<input type="submit" name="Button" id="Save" value="Save" class="btnSave" />
<div id="phoneList" class="phoneList">
<table>
<% foreach (var item in Model.Phones)
{ %>
... Stuff omitted for space ....
<% } %>
<tr>
<td colspan="2">
<input type="submit" id="Add" name="Button" value="Add another phone" class="btn_AddPhone" />
</td>
</tr>
</table>
<% } %>
</div>
</div>
source to share
Two ways:
First a string parameter for your Create function named Button
public ActionResult Create(string Button)//and other fields
{
if (Button == value1) then
//do stuff
else if (Button == value2) then
//do stuff
end if
//return
}
Where value1 = "Add another phone"
If you pass it using a collection of forms it would be
if (formcollection ["Button"] == value1) ....
source to share
This might be too simple, but why not just use the PostBackUrl attribute on every submission control and add a parameter to its initiative?
For example,
<asp:Button ID="Button1" runat="server" Text="Button One"
PostBackUrl="Text.aspx?b=1" UseSubmitBehavior="true" ... / >
<asp:Button ID="Button2" runat="server" Text="Button One"
PostBackUrl="Text.aspx?b=2" UseSubmitBehavior="true" ... / >
The parameter "b" to querystring can be written on the server side:
string mode = HttpContext.Current.Request.QueryString["b"].ToString();
... and then you do different things based on the value of the mode variable in this case.
source to share