繁体   English   中英

JavaScript无法在单独的文件中工作

[英]JavaScript not working from separate file

我正在尝试将JS移到单独的文件中,而不是直接将其放在页面上。 但是,由于某种原因,我无法使其正常运行。

我想根据下拉菜单选择更新站点。 我现在的操作方式是:

视图:

<script type="text/javascript">
$(document).ready(function () {
    $("#EntityType").change(function () {
        /* Get the selected value of dropdownlist */
        var selectedID = $(this).val();

        /* Request the partial view with .get request. */
        $.get('/Entity/Create_DropDownList/' + selectedID, function (data) {

            /* data is the pure html returned from action method, load it to your page */
            $('#entity_form_attributes').html(data);
            /* little fade in effect */
            $('#entity_form_attributes').fadeIn('fast');
        });
    });
});
</script>

    <div class="editor-field">
        @Html.DropDownList("EntityType", (SelectList)ViewData["Types"])
    </div>

    <div id="entity_form_attributes"></div>

可以了 局部视图应按原样加载到div标签中。 但是,如果创建一个JavaScript文件,然后将脚本移入该文件,它将失败。 在共享的起始站点中,我包含了JavaScript文件。

谁能看到我在做什么错。 该应用程序是MVC3应用程序。 我需要设置某种设置/属性才能使其正常工作吗?

谁能看到我做错了什么。

是的,您已经在此处对网址进行了硬编码,而不是使用Url帮助程序来生成它。 您绝对不应这样做:

$.get('/Entity/Create_DropDownList/'

当您在IIS中部署应用程序时,这会中断,因为您的URL错误。 由于使用此硬编码的url,因此您省略了在开头包含虚拟目录名称的操作。

因此,在ASP.NET MVC应用程序中处理URL时,请始终使用Url帮助器。 因此,根据您的情况,您可以在视图中将此URL生成为HTML5 data-*属性:

@Html.DropDownList(
    "EntityType", 
    (SelectList)ViewData["Types"], 
    new { data_url = Url.Action("Create_DropDownList", "Entity") }
)

然后在单独的javascript文件中只需检索以下网址并使用它即可:

$("#EntityType").change(function () {
    /* Get the selected value of dropdownlist */
    var selectedID = $(this).val();

    /* Get the url from the data-url HTML attribute */ 
    var url = $(this).data('url');

    /* Request the partial view with .get request. */
    $.get(url, { id: selectedID }, function (data) {
        /* data is the pure html returned from action method, load it to your page */
        $('#entity_form_attributes').html(data);
        /* little fade in effect */
        $('#entity_form_attributes').fadeIn('fast');
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM