views:

312

answers:

2

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

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

W_P
Sorry I took out too much when I tried to simplify the code for my question. The call is in a script block and the jquery is loaded before the site.js. I've edited the question...thanks for keeping me right though! :)
Boob
I don't know if this is how it works with asp.net (i'm a php guy) but if i want something in a .js file to be evaluated server-side, I have to give the file a .php extension. I'll edit my answer to explain more...
W_P
+2  A: 

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