3

I am unable to determine which form submit button is clicked during an Ajax Form POST in ASP.NET MVC. I have a form that basically looks like:

    <% using (Ajax.BeginForm("Edit",
                             new { code = Model.Code },
                             new AjaxOptions() {
                                UpdateTargetId = "resultsDiv"
                             })) {%>
    <p>
       <%= Html.TextBox("Name", Model.Name)%>         

       <input id="submitButton1" name="submitAction" class="ajaxSubmitButton"
              type="submit" value="Button 1" />
       <input id="submitButton2" name="submitAction" class="ajaxSubmitButton" 
              type="submit" value="Button 2" />

       <input id="testHiddenValue" name="testHiddenValue" 
              type="hidden" value="hello world!" />
    </p>

<% } %>

After a standard HTTP POST (ie. JavaScript disabled), I get access to the following POST variables:

  • Name = whatever
  • submitAction = Button 1
  • testHiddenValue = hello world!

However, clicking that button with JavaScript enabled does not include the submitAction value. I have verified this by inspecting the POSTs with Fiddler.

My hunch is that the Microsoft Ajax library just doesn't serialize the values of the submit buttons. In any case, how can I get around this so my controller knows which button was clicked?


Edit: Yes, it looks like a bug in the Microsoft Ajax library (see below). To workaround this, I essentially added the following jQuery code:

$(document).ready(function() {           
    $("#formId .ajaxSubmitButton").live("click", function() {                
        $("#testHiddenValue").attr("value", $(this).attr("value"));
    });    
});

Then in my controller, if Request.IsAjaxRequest() == true, I can check the value of #testHiddenValue. Otherwise, I can look in Request.Form["submitAction"] and determine the correct course of action from there.

Fairly clunky, but I can't really see an alternative.

intoOrbit
  • 2,122
  • 2
  • 19
  • 21
  • does this approach work if it were a regular form as opposed to an ajax form? – Amir Sep 22 '09 at 19:32
  • I haven't tried that, but I assume so. It works when you disable JavaScript. A similar suggestion (for a regular form) is here: http://stackoverflow.com/questions/442704/how-do-you-handle-multiple-submit-buttons-in-asp-net-mvc-framework – intoOrbit Sep 22 '09 at 19:35

1 Answers1

2

See here. It looks like this is a bug. Personally I would investigate injecting the button name you wish to know about into a hidden form field as a temporary fix.

Community
  • 1
  • 1
RichardOD
  • 28,883
  • 9
  • 61
  • 81
  • I guess it is Microsoft's bug. Injecting the button name into a hidden field is exactly the workaround I had planned. I will edit my original post with the code when I have it. – intoOrbit Sep 22 '09 at 19:53