David Williams
David Williams

Reputation: 390

Ajax.BeginForm() not sending submit button's name/value

I have the following code and when I click the submit button its name and value isn't being sent to the server

@using(Ajax.BeginForm(new AjaxOptions{Url = "http://localhost/controller/action"}))
{
    <button name="action" type="submit" value="Save">
        <span>Save</span>
        <!-- More HTML tags here -->
    </button>
}

I had a look in the jquery.unobtrusive-ajax.js file to see if it should send the name/value of the button that was clicked and found this code that attaches these values as an attribute to the form which is later passed along in the post request.

$("form[data-ajax=true] :submit").live("click", function (evt) {
    var name = evt.target.name,
        form = $(evt.target).parents("form")[0];

    $(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);

    setTimeout(function () {
        $(form).removeData(data_click);
    }, 0);
});

The values of evt.target.name and evt.target.value contained the name/value from the HTML element within the button tag that registered the click.

I managed to get it to work by replacing evt.target with evt.currentTarget in the above code but I'm a bit worried this may have unintended side effects.

Is there a better way to send the submit button's name/value to the server?

Upvotes: 1

Views: 902

Answers (1)

Wheelie
Wheelie

Reputation: 3916

I've reproduced the problem you describe and your proposed code fix seems to do the trick for me.

I can understand your reluctance in modifying the standard jquery.unobtrusive-ajax.js library since you'll have to remember to merge your changes when a new version is released. A better option would be to submit a patch so your fix can be reviewed and hopefully incorporated into the standard library. I don't know the best way of going about this but I believe that a large proportion of ASP.NET code is now open source, including MVC, and that Microsoft have begun to accept code contributions from the community. I would suggest having a look at http://aspnetwebstack.codeplex.com/ for more info.

As an alternative to changing the library, have you considered eliminating the need to include child elements inside your button? If your button only contains text (and no tags) the standard library works correctly and posts the button's name and value. If you need images you may be able to get away with using the CSS background-image property instead of a nested img tag.

Upvotes: 1

Related Questions