【问题标题】:aspmvc2 render partialview with jquery using spark engineasp mvc 使用 spark 引擎使用 jquery 渲染部分视图
【发布时间】:2010-10-08 16:50:36
【问题描述】:

我正在尝试在用 spark 渲染的 asp mvc2 中返回部分视图。 该视图包含一些 javascript。 一切都被渲染了,但脚本没有执行

这里是代码

<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>

我做错了什么? 谢谢

【问题讨论】:

    标签: jquery asp.net-mvc-2 spark-view-engine


    【解决方案1】:

    Jquery Ajax 函数将从结果中去除 javascript 并在将 HTML 插入 DOM 之前运行它。

    您的两个最佳选择是任一

    将 JS 封装在视图的非 ajax 部分(视图或同时呈现的部分)上的函数中,并将此函数作为 ajax 调用的成功回调调用

    或者将 $("#SourceList").change(function() { 替换为 $("#SourceList").live('change', function() { 尽管即使这样做,您最好还是不要将其作为通过 Ajax 返回的部分包含在内。

    【讨论】:

      【解决方案2】:

      我会将脚本放在 jQuery 文档就绪事件处理程序中,以便在 DOM 完全加载后运行。可能是脚本在 DOM 创建您的 #SourceList 之前正在运行。

      例如:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-18
        • 2011-04-08
        • 2015-09-18
        • 1970-01-01
        • 2020-12-21
        • 2010-12-06
        • 2023-03-30
        相关资源
        最近更新 更多