简体   繁体   中英

JavaScript not working from separate file

I'm trying to move my JS into a separate file, instead of having it directly on the page. But, for some reason, I can't get it working.

I want to update a site depending on a dropdown selection. The way I'm doing it now is this:

View:

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

This is working. A partial view is loaded into the div tag as it should. But if a create a JavaScript file and then move the script into the file, it fails. From a shared start site I'm including the JavaScript file.

Can anyone see what I'm doing wrong. The application is a MVC3 application. Is there a setting/property I have to set to make this work?

Can anyone see what im doing wrong.

Yes, you have hardcoded the url here instead of using Url helpers to generate it. You should never do that:

$.get('/Entity/Create_DropDownList/'

This will break when you deploy your application in IIS because your url is wrong. Due to this hardcoded url you have omitted to include the virtual directory name in the beginning.

So always use Url helpers when dealing with urls in an ASP.NET MVC application. So in your case you could generate this url in the view as a HTML5 data-* attribute:

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

and then in your separate javascript file simply retrieve this url and use it:

$("#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');
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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