0

My Main View:

@Ajax.ActionLink("append smth", "AddSmth", new AjaxOptions { UpdateTargetId = "smthContainer", InsertionMode.InsertAfter })

<div id="smthContainer"></div>

My Controller:

public ActionResult AddSmth()
{
    return PartialView("Smth");
}

Smth partial view:

<input type="text" id="dateOfSmth" />

<script type="text/javascript">
$(document).ready(function () {
    $('#dateOfSmth').datepicker();
});
</script>

The problem is that ready function is called before partial view is added to document, so $('#dateOfSmth') is empty. Everything works fine if I replace InsertionMode.InsertAfter with InsertionMode.Replace. Do you have any idea why is not it woking correctly with InsertionMode.InsertAfter?

EDIT: works well when appending view with jQuery:

<a href="javascript:addSmth();"> Add Smth </a>

<script type="text/javascript">
                function addSmth() {
                    $.get('@Html.Raw(Url.Action("AddSmth"))', null, function (view) {
                        $('#smthContainer').append(view);
                    });
                }
</script>
karaxuna
  • 26,752
  • 13
  • 82
  • 117

2 Answers2

1

The code below is from the jQuery codebase:

 // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
    if (!document.body) {
        return setTimeout(jQuery.ready, 1);
    }

So the ready event waits till the body element has been created. If the partial view is added after body element has been created then that is why your function is executing too early.

In theory you could do something similar to execute code after the partial view has been loaded.

function createDatePicker( ) {

    if ( !document.getElementById("dateOfSmth") ) {

        return setTimeout( createDatePicker, 1);
    }

    // do stuff
}
Bruno
  • 5,772
  • 1
  • 26
  • 43
  • Body element is created in every case because I add partial view using ajax. Something wrong is with InsertionMode.InsertAfter. See questioin update – karaxuna Nov 12 '12 at 11:30
1

The ready event is fired a single time - when the DOM has finished being loaded - and doesn't fire again when you insert AJAX loaded content. If you add a ready event handler after that has happened then it will be executed automatically.

The problem is probably caused by a difference in how the two insertion modes - InsertionMode.InsertAfter and InsertionMode.Replace - handle <script> tags in the content.

If you can, simply call your:

$('#dateOfSmth').datepicker();

line after the AJAX content has been loaded.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • 1
    1. ready event IS fired every time partial view is added 2. after setting timeout $('#dateOfSmth').datepicker(); works – karaxuna Nov 12 '12 at 11:49