开发者

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

开发者 https://www.devze.com 2022-12-25 11:36 出处:网络
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:

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?


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 });
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号