ASP.NET MVC jQuery autocomplete with url.action helper in a script included in a page

瘦欲@ 提交于 2019-12-12 09:18:23

问题


I have been building my first ASP.NET MVC web app. I have been using the jQuery autocomplete widget in a number of places like this:

<head>
    $("#model").autocomplete({ source: '<%= Url.Action("Model", "AutoComplete") %>' });
</head>

The thing is I have this jQuery code in a number of different places through my web app. So i thought I would create a seperate javascript script (script.js) where I could put this code and then just include it in the master page. Then i can put all these repeated pieces of code in that script and just call them where I need too. So I did this. My code is shown below:

In the site.js script I put this function:

function doAutoComplete() {
    $("#model").autocomplete({ source: '<%= Url.Action("Model", "AutoComplete") %>' });
}


On the page I have:

<head>
    <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="../../Scripts/site.js" type="text/javascript"></script>
    <script type="text/javascript">
        doAutoComplete();
    </script>
</head>

But when I do this I get an Invalid Argument exception and the autocomplete doesnt work. What am I doing wrong? Any ideas?Do i need to pass something to the doAutoComplete function?


回答1:


The <%= will not be evaluated in your external javascript.

Solution: pass the URL as a parameter to your javascript function.

<script>
    doAutoComplete('<%= Url.Action("Model", "AutoComplete") %>');
</script>

function doAutoComplete(url) {
    $("#model").autocomplete({ source: url });
}



回答2:


You need to put the function call in a script block, and make sure jquery is loaded before your site.js ...

<head>
    <script src='path/to/jquery.js'></script>
    <script src="../../Scripts/site.js" type="text/javascript"></script>
    <script>
    doAutoComplete();
    </script>
</head>

EDIT:

Maybe the '<%= ... =%>' tag isn't being evaluated server-side, before the function gets sent to the browser? Here is an article on this: http://www.west-wind.com/weblog/posts/252178.aspx

Here is a quote from the post:

There's also a problem if you need access to the [ASP.NET] variables in .js files - you can't embed script tags into a .js file so getting a dynamic value into a static file is problematic



来源:https://stackoverflow.com/questions/2553377/asp-net-mvc-jquery-autocomplete-with-url-action-helper-in-a-script-included-in-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!