Monday, May 18, 2009

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.

3 comments:

  1. 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!

    ReplyDelete
  2. 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?

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

    ReplyDelete