views:

93

answers:

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

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

Eilon
in my syantaxshowalert('invalidusername','password')--- this is java script funtion. i am passing parametersi have doubt in your syntax: what is mykey---is it javascript funtion
vasanth
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
still i got error this funtion i wrote in javascript filefunction 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
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
Thanks, I got the answer
vasanth