1

I have to call javascript function from javascript file codebehind .aspx page . Presently I am using this syntax which is giving me an error.

this.Page.ClientScript.RegisterClientScriptInclude
    ("showalert('invalidusername','password')","/Public/JS/FailLogin.js");
2
  • 2
    Why are you using something that looks like Javascript as key? Do you expect the key to be executed as Javascript? Commented Jan 6, 2010 at 1:27
  • Upvoting this back to 0 because the question is perfectly valid. Obviously if the asker knew how to use this method they wouldn't be asking the question in the first place. Commented Jan 6, 2010 at 1:38

1 Answer 1

2

You're calling the right method but as Guffa says, you're passing it invalid parameters.

Try something like this instead:

this.Page.ClientScript.RegisterClientScriptInclude("myKey",
    "/Public/JS/FailLogin.js");

Or if you want inline script:

this.Page.ClientScript.RegisterClientScriptBlock(GetType(),
    "myKey", "alert('whatever')");

Or to pass in some more dynamic script:

string name = "Joe";
string script = "alert('Your name is" + name + "')";
this.Page.ClientScript.RegisterClientScriptBlock(GetType(),
    "myKey", script);

Please note that in the last example you most JavaScript encode the value of the "name" field. Depending on the version of .NET, one way to do it is this:

string encodedName = JavaScriptSerialize.Serialize(name);

And then pass the encoded name to the "script" variable.

You can even call both methods if you want to both include a JS file as well as run some code that depends on the newly included JS file (the script include should be rendered before the script block).

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

4 Comments

in my syantax showalert('invalidusername','password')--- this is java script funtion. i am passing parameters i have doubt in your syntax: what is mykey---is it javascript funtion
The "mykey" is any string that you want. It's just to tell ASP.NET the "name" of your script so that in case you include it twice in the same page it will know that it's a duplicate and it'll only render it once. I updated my answer to show a more dynamic example of the script.
still i got error this funtion i wrote in javascript file function showalert(invalidusername,password ){ alert('country'+invalidusername+ ''+password+'place'); } stil i am getting error but i calling like: is it correct? Page.ClientScript.RegisterClientScriptInclude("mykey", "/Public/JS/FailLogin.js");
Please update your original question with more details about what you're doing. Your code looks right but it's hard to tell when it's in one of these small comments.

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.