views:

21

answers:

2

I'm trying to return a partial view in asp mvc2 rendered with spark. The view contains some javascript. Everything gets rendered but the script does not execute

here is the code

<table>
<tr>
<td> 
    !{Html.LabelFor(model => model.SourceId, new { @class = "label-inline", title = "Source d'ouvrage" })}
    !{Html.DropDownList("SourceList", Model.SourceList, "Choisir la source", new { @class = "combo-box" })}
</td>
<td>
    !{Html.LabelFor(model => model.AgentId, new { @class = "label-inline", title = "Représentant" })}
    !{Html.DropDownList("AgentList", Model.AgentList, "Choisir le représentant", new { @class = "combo-box" })}
</td>
</tr>

<script type="text/javascript">
$("#SourceList").change(function() {
    alert('youpi');
    $.ajaxSetup({ cache: false });
        var selectedItem = $(this).val();
        alert(selectedItem);
        if (selectedItem == "" || selectedItem == 0) {
            //Do nothing or hide...?
        } else {
            var path = '~/sources/' + selectedItem + '/agents';
            $.getJSON(path, function(data) {
                agents = data;
                var items = "";
                $.each(data, function(i, agents) {
                    items += "<option value='" + agents.Id + "'>" + agents.Name + "</option>";
                });
                $("#AgentList").html(items);
            });
        }
    });
</script>

What i'm i doing wrong? thanks

A: 

Jquery Ajax functions will strip the javascript out from the result and run it before inserting the HTML into the DOM.

Your two best options are either

Wrap the JS in a function on the non-ajax part of the view (either the view or a partial that's rendered at the same time) and call this function as your success callback on your ajax call

Or replace $("#SourceList").change(function() { with $("#SourceList").live('change', function() { though even doing this you're still better off not including it as the partial returned via Ajax.

Chao
A: 

I would put the script inside the jQuery document ready event handler so that it gets run AFTER the DOM has fully loaded. it could be the script is running before the DOM creates your #SourceList.

ex:

<script type="text/javascript">
    $(function() {
        $("#SourceList").change(function() {
            ....
dave thieben