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>

      

+2


source to share


3 answers


I would be tempted to add that I would use two forms, each with one submit button, to ensure that each form has only one responsibility. This will help separate concerns and make the application more testable.



+3


source


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) ....

+3


source


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.

+1


source







All Articles