views:

406

answers:

1

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.

+2  A: 

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.

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