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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.