1

In a c# aspx project. I can reach a static method on client side with importing my namespace at the beginning part of the page, as follows.

<%@ Import Namespace="utl=portal.library.Utilities" %>

And than in can use that on client side of the same asxp page like.

<script type="text/javascript">
var categoryPage;
categoryPage = '<%= utl.getcategoryName().ToString() %>';
</script>

My question is, can i use that '<%= utl.getcategoryName().ToString() %>' in an external javascript file ?

Is it possible something like that ?

<%@ Import Namespace="utl=portal.library.Utilities" %>
<script src="/scripts/trial.js" type="text/javascript"></script>

and in the trial.js file

var categoryPage;
categoryPage = '<%= utl.getcategoryName().ToString() %>';

thanks in advance..

Bakudan
  • 19,134
  • 9
  • 53
  • 73
Adam Right
  • 955
  • 6
  • 17
  • 35

3 Answers3

1

I don't think so, because the external .JS file wouldn't be processed by ASP.NET and therefore wouldn't have access to those kinds of variables.

James
  • 13,092
  • 1
  • 17
  • 19
  • depending on IIS version this is not necessarily true. From version 7 and up, your able to run the website in Integrated Mode which means all requests can be handles by asp.net, .js, extensionless and so on so you could easily write a generic asp.net handler and configure it to respond to scripts/trial.js – Pauli Østerø Jan 15 '12 at 23:01
0

I don't think you can but you could instead try to pass the server side variable as a parameter to a JS function in the external JS file.

Shirlz
  • 837
  • 2
  • 11
  • 18
0

You can create a .aspx file that only outputs Javascript instead of HTML. As long as you set the Content Type to application/x-javascript in the code behind, it will work.

For example, create Test.js.aspx. Then, in the code behind for Test.js.aspx.cs:

protected void Page_Load( object sender, EventArgs e )
{
    Response.ContentType = "application/x-javascript";
}

protected string GetMessage()
{
    return "Hello, World!";
}

In the Test.js.aspx file:

window.onload = function() { 
    var msg = <%=GetMessage() %>
    alert(msg); 
}

Now, it is true that the Javascript running on the client can't call C# functions running on the server. You would need AJAX for that. But you can certainly use this pattern to generate Javascript that make use of ASP.NET when it is generated.

Katie Kilian
  • 6,815
  • 5
  • 41
  • 64
  • you don't need it to be an .aspx file. Just write an generic asp.net handler and configure it in web.config to respond to scripts/trial.js – Pauli Østerø Jan 15 '12 at 23:02