.net Mvc 3 Ajax.BeginForm, get the form element
Asked Answered
G

3

5

I'm trying to work with the form dom element with the OnBegin & OnComplete routines of the Ajax.BeginForm helper in Mvc.

Currently I have this:

@using (Ajax.BeginForm("Contact", "Home", new AjaxOptions { OnBegin = "handleOnBegin" }))

But within the OnBegin / OnComplete handlers, I want to work with the form dom element - is this going to be possible? I've checked the arguments passed to those handlers and I can't see anything.

function handleOnBegin(a, b){
  var f = <get form>;
  animateForm(f);
}

I've even tried passing 'this' with the handlers but that only seems to pass the XHR object (or something similar)... Also, I'm reluctant to tit about with passing id's and adding more code as I'm convinced there's a simpler way.

Gans answered 30/7, 2011 at 16:4 Comment(0)
G
6

An an ID to your form as the 4th parameter to Ajax.BeginForm:

@using (Ajax.BeginForm("Contact", "Home", 
        new AjaxOptions { OnBegin = "forms.onBegin", OnComplete = "forms.onComplete" },
        new { id = "FormName" }))

Then you can select the form by ID (#FormName).

Edit:

Or see the answers to this question

Grume answered 30/7, 2011 at 16:8 Comment(2)
I agree this is an option, but I don't want to add specific form id's in a generic library which is handling these callbacks. Separation of concerns and all that, i'd rather the handler work this out somehow.Gans
This signature does no longer work in MVC5. It should be Ajax.BeginForm("Contact", "Home",null, new AjaxOptions, new HtmlAttributes Noitce the null for routevalues.Bibliophile
D
1

I looked at the arguments also and can't see anything that will help out of the box. Another option is to add a function to your library that will add an onclick event handler to the buttons on your page. Something like

var clickedBtnID = null;
$(document).ready(function()) {
    $(input[type=submit]).click(function() {
        clickedBtnID = $(this).attr("id");
    }
}

Then you can access clickedBtnID from your callback function. Not a perfect solution but it might be general enough.

Dwaynedweck answered 31/7, 2011 at 10:45 Comment(1)
This won't work because it will run the event before the ajax request. OnSuccess and OnComplete occur after the ajax request, however submit click will occur before.Exult
J
0

Give CSS classes to the DOM elements you want to work with. So you can find the elements by CSS classes, even if the form is in a partial, and nested in other elements for example.

Something like this:

$form.find(".labelToUpdate").text(response.labelText);
Judenberg answered 30/7, 2011 at 16:16 Comment(1)
what if you have many .labelToUpdate - suddenly that becomes a problem :(Bibliophile

© 2022 - 2024 — McMap. All rights reserved.