C# ASP.NET SQL SERVER

Which button was clicked in the ASP.NET MVC View?

In an ASP.NET MVC view you might have multiple "submit" buttons inside a <form> such as:

<% using (Html.BeginForm()) {%>
  <fieldset>
    <p>
       <input type="submit" value="Create" name="create" />
       <input type="submit" value="Cancel" name="cancel" />
    </p>
  </fieldset>
<% } %>

The Html helper extension method BeginForm() will emit an opening and closing <form> tag that encloses the input fields.

Your controller that accepts the POST verb will look something like this:

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                string create = Request.Form["create"];
                string cancel = Request.Form["cancel"];

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

If the Create button was clicked then the create variable will be set to "Create" (because "Create" is the value set to the input named "create") and the cancel button will be set to null. The opposite is true if the Cancel button is clicked.

» Similar Posts

  1. ASP.NET MVC with jQuery DynaTree plugin for Checkboxes
  2. ASP.NET MVC DropDownList from Enum
  3. Combine, compress, and update your CSS file in ASP.NET MVC

» Trackbacks & Pingbacks

    No trackbacks yet.
Trackback link for this post:
http://guyellisrocks.com/trackback.ashx?id=160

» Comments

  1. Simon avatar

    This almost works but if I have a textbox with some jQuery validation for some reason it 'loses' the value for the button pressed. It's really annoying!

    Simon — October 14, 2009 9:59 AM
  2. Robert avatar

    I tried this and it definitely returns the value of the button clicked. However, I am doing client-side validation using and when the Cancel button is clicked it insists on having valid data before posting back, even when I have causesvalidation set to false.

    <input type="submit" value="Cancel" name="cancel" causesvalidation="false" />

    That's not of much use for a cancel button, since why would I want valid data on a cancel?

    Robert — December 15, 2010 12:25 PM
  3. guy ellis avatar

    Robert - in that case you would completely remove the causesvalidation attribute instead of setting it to false.

    guy ellis — December 15, 2010 3:21 PM

» Leave a Comment