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?
    – Guffa
    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.
    – Eilon
    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).

4
  • 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
    – vasanth
    Commented Jan 6, 2010 at 1:56
  • 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.
    – Eilon
    Commented Jan 6, 2010 at 2:04
  • 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");
    – vasanth
    Commented Jan 6, 2010 at 2:23
  • 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.
    – Eilon
    Commented Jan 6, 2010 at 18:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.