Determining which submit button was used to POST a form in asp.net MVC
I have a view in asp.net MVC that has two submit buttons. I would like to k开发者_JS百科now which button was pressed. The buttons work GREAT so there is no issue there, I just need to do slightly different things depending on which button. I have checked the Request.Form[] collection and that doesn't contain 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>
I'd be tempted to add that I'd have used two forms, each one with a single submit button to ensure that each form only had a single responsibility. That would aid the separation of concerns and make the app more testable.
Two ways:
First, a string parameter to 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 are passing it in with the form collection, then it would be
if (formcollection["Button"] == value1)....
Perhaps this is too easy, but why not simply use the PostBackUrl attribute in each submit control, and add a parameter to its querystring?
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 "b" querystring parameter can be captured on the server-side:
string mode = HttpContext.Current.Request.QueryString["b"].ToString();
... and then you do different things based upon the value of, in this case, the mode variable.
精彩评论