Muflix Muflix - 23 days ago 11
Ajax Question

Ajax.BeginForm - How to access new DOM objects from PartialView?

I have following div, which is loading Partial View

<div id="_customerForm">
@Html.Partial("~/Views/Customer/_customerForm.cshtml", Model.customerForm)
</div>


In that Partial View I have Ajax Form

@using (Ajax.BeginForm("UpdateCustomer",
"Customer",
new AjaxOptions()
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "_customerForm",
}
))
{
...
}


And When I submit the Ajax Form, the Partial View, including Ajax Form, is regenerated (by new model from server)

The problem I am facing is that I have jquery event attached to one of the input of that form, which works, until the form is refreshed. For example

$("#CustomerAddressList").change(function () { ... });


Change event on
#CustomerAddressList
DOM works until
#CustomerAddressList
is refreshed by new PartialView model, any idea ?

Answer

Use

$(document).on("change", "#CustomerAddressList", function(){
...
});

or

$("body").on("change", "#CustomerAddressList", function(){
...
});

Because the listener is bound to an element which is persistent on the page, it doesn't matter if the item which the selector references is dynamic content or not.

.on documentation.

Comments