C # background calling foreground and JS method intermodulation

Source: Internet
Author: User

C # Background calling foreground and JS method intermodulationCategory: Learn a little 2009-10-22 every day 00:32 1527 people read reviews (0) favorite reports C#javascript Script buttonvbscriptstring

Many people are working with functions that invoke clients on the server side, which is called scripting functions already defined in the JavaScript script in ASP. After studying, some reluctant methods have been found.

1. Writing scripts using the Response.Write method

For example, after you click the button, the database is finished, the display is finished, you can write in the last place to call
Response.Write ("<script type= ' Text/javascript ' >alert ();</script>");

One drawback of this approach is that you cannot invoke a custom function in a script file, only call an intrinsic function, and call a custom function to write function definitions only in Response.Write, such as Response.Write ("<script type= ' text/ JavaScript ' >function myfun () {...} </script> ");

2. Dynamically add scripts with the ClientScript class

Use the following: Add code where you want to invoke a JavaScript script function, and be sure that Myfun has already been defined in the script file.

Clientscript.registerstartupscript (Clientscript.gettype (), "MyScript", "<script>myfun ();</script>");

This method is more convenient than Response.Write, you can directly invoke the custom function in the script file.

3. Attributes properties for normal add controls

For the normal button is: Button1.Attributes.Add ("onclick", "myfun ();");

Only valid if added in onload or in the initialization process similar to onload. The script function is executed first, and the execution order cannot be changed.

Note that all of the above methods, the background code can not be converted to the current page of the code, such as redirect, to put the paging code in the script

Ask:

1. How do I access C # functions in JavaScript?

2. How do I access C # variables in JavaScript?

3. How do I access the existing variables of JavaScript in C #?

4. How do I access JavaScript functions in C #?

Question 1 answers are as follows:

The functions in the C # code are executed in the JavaScript function:

Method One: 1, first set up a button, in the background will be called or processed content written in Button_Click;

2, write a JS function in the foreground, the content is document.getElementById ("Btn1"). Click ();

3, in the foreground or background call JS function, fire click event, equal access to the background C # function;

Method Two: 1, function declaration is public

Background code (change public to protected also can)

public string SS ()

{

Return ("a");

}

2, in the HTML with <%=fucntion ()% > can be called

Foreground script

<script language=javascript >

var a = "<%=ss ()% >";

alert (a);

</script >

Method Three: 1, <script language= "JavaScript" >

<!--

function __doPostBack (Eventtarget, eventargument)

{

var theform = document.     Form1; Refers to the form of runat=server

Theform.__eventtarget.value = Eventtarget;

Thefrom.__eventargument.value = eventargument;

Theform.submit ();

}

-->

</script >

<input id= "Button1" type= "button" Name= "Button1" value= "buttons" onclick= "Javascript:__dopostback (' Button1 ', ')" >

Method Four: <script language= "JavaScript" >

function Submitkeyclick ()

{

if (Event.keycode = = 13)

{

Event.cancelbubble = true;

Event.returnvalue = false;

Document.all.funname.value= "The name of the function you want to invoke";

Document.form[0].submit ();

}

}

</script >

<input onkeypress= "Submitkeyclick ()" id= "AAA" type= "text" >

<input type= "hidden" name= "Funname" >〈! --Used to store the function you want to call--〉

In. cs There are:

Public Page_onload ()

{

if (! Page.ispost ())

{

String strfunname=request.form["Funname"]!=null? request.form["Funname"]: "";

Determines which function to call based on the value returned

Switch (strfunname)

{

Case "Enter ()":

Enter (); Call this function

Break

Case "Other":

Calling other functions

Break

Default

Calling the default function

Break

}

}

}

public void Enter ()

{

...... such as calculating a value

}

Question 2: How do I access C # variables in JavaScript?

The answers are as follows:

Method One: 1, through the page hidden domain access <input id= "xx" type= "hidden" runat= "Server" >

Method Two: 1, such as the background defines the public STRING N; The format for referencing the variable in the foreground JS is ' <%=n% > ' or ' + <%=n% >+ '

Method Three: 1, or you can register a script on the page after the server-side variable is assigned a value

"<script language= ' JavaScript ' >var temp=" + tmp + "</script >"

TMP is a background variable, and then JS can directly access the temp to get the value.

3. How do I access the existing variables of JavaScript in C #?

The answers are as follows:

Method One: 1. The foreground uses the static text control to hide the field and writes the value of the JS variable to it;

2, backstage with request["id" to get the value;

Method Two: You can use a cookie or session

4. How do I access JavaScript functions in C #?

The answers are as follows:

Execute JavaScript functions in C # code:

Method One: 1, page.registerstartupscript ("GGG", "<script >setvisible (1); </script >");

Method Two: Use the literal class, and then

private void Button2_Click (object sender, System.EventArgs e)

{

String str;

str= "<script language= ' JavaScript >";

str+= "Selectrange ()";

str+= "</script >";

Literal1.visible=true;

LITERAL1.TEXT=STR;

}

1. Background method:

Protected string Csharpvoid (String STRCC)

{

return STRCC;

}

2.javascript Call

<script>

var s = "<%=csharpvoid (" <a href= "http://www.esoutong.com")%/">www.esoutong.com")%> ";

document.write (s);

</script>

+++++++++++++++++ Second case:

1. Post Code:

protected void csharpvoid ()

{

String STRCC = "www.esoutong.com";

Response.Write (STRCC);

}

2. Calling method: Csharpvoid ()

<script>

document.write ("<%csharpvoid ();%>");

</script>

You can put a button in the page, set it to invisible style= "Display:none", and then use the script to let this button click

document.all ("Button1"). Click ();

Write the event code in the C # Background of this button, which is the simplest script to call the C # method.

On the Internet to see a problem: the author of the platform is. NET, in C # in the native development, in the ASPX file called JS file:

<script language= "javascript" src= "Mymenu.js" ></script>

Results on the page and alert prompt in Chinese are garbled, to find a solution. The result behind keep abreast gives a long list of solutions, in fact, it is very simple to add a line of code in the head of the aspx file:

<!--page contenttype= "text/html" responseencoding= "gb2312"-

Very simple, hehe. <!--page contenttype= "text/html" responseencoding= "gb2312"--<script language= "javascript" type= "text/ JavaScript "src=" treeview.js "></script><script language=" JavaScript "type=" Text/javascript "src=" Treeview.js "></script>

--------------------------------------------------------------------------------------------------------------- -----------------------------------

Invoke implementations of scripts such as VBScript, JavaScript, and so on in C #

Autumn Maple

Previously in the work Flow (workflow) project, one of the items is that when the user formulates the process definition can write scripts to control the activities of the jump, and these scripts are defined in the database, when the process starts, the workflow engine will control the execution sequence of activities, string type of two activities is relatively simple, But some activities to the next activity have conditional judgment, or there are multiple branches, simple fortunately, as long as the database table in the addition of a field can be implemented, a little more complex need to be implemented through the script. There was not enough experience, a few days to find a quick solution, I want to write a custom scripting engine is not sure, and time is not enough, or to look at the Internet, took some time, or found a self-think better solution, write to share with you.

Here are two parts to illustrate implementation and application.

A Using Msscriptcontrol

To the Microsoft Web site, download Windows Script control, which is an ActiveX (R) control, so the. NET use I interop a bit. After the download installation is complete, create a new C # Windows Application project, select the reference node in Solution Explorer, right-click the Select Add Reference menu, pop up the Add Reference dialog box, click Browse to locate the directory where Windows Script control is installed. Select the MSScript.ocx file to determine. Then a Msscriptcontrol component is added under the reference node, and the following is all the objects after his interop.

The ScriptControl provides a simple interface to the host script engine that supports ActiveX (TM) script. Next we explain the properties and methods of the ScriptControl that are converted to the Scriptcontrolclass class.

Property

Allowui property: The user interface element that is applied to the ScriptControl itself or the SCIRPT engine is readable and writable.

CodeObject property: Returns the object that is used to invoke the public member of the specified module. Read-only.

Error property: Returns the Error object that contains the details about the last error that occurred. Read-only.

Language Property: Sets or returns the name of the Script language being used. can read and write.

Modules property: Returns a collection of modules for the ScriptControl object. Read-only.

Procedures property: Returns the collection of procedures defined in the specified module. Read-only.

Sitehwnd Property: Sets or returns the HWnd of the window, which is used to display dialog boxes and other user interface elements by executing the Script code. can read and write.

State property: Sets or returns the mode of the ScriptControl object. can read and write.

Timeout Property: Sets or returns the time (in milliseconds) after which the user can choose to abort the execution of the Script code or allow the code to continue executing. can read and write.

Usesafesubset Property: Sets or returns a Boolean value that indicates whether the host application has a privacy requirement. Usesafesubset is True if the host application requires security control, otherwise False. can read and write.

Method

Addcode method: Adds the specified code to the module. The Addcode method can be called multiple times.

AddObject method: Make the Host object model available to the Script engine.

Eval method: Evaluates an expression and returns the result.

Executestatement method: Executes the specified statement.

Reset method: Discards all Script code and objects that have been added to the ScriptControl.

Run method: Runs the specified procedure.

Event

Error Event: This event occurs when a run-time error occurs.

Timeout Event: This event occurs when the time specified by the timeout attribute is exceeded and the user selects End in the Results dialog box.

Additional points

The Allowui property, if set to false, shows statements such as dialog boxes that do not work, such as MsgBox statements in VBScript, alert in JavaScript, and so on, and if the executed script exceeds the number of milliseconds set by timeout, Also does not jump out of the dialog box that exceeds the time alert, and vice versa; The reset Language property empties the Addcode loaded code, and for the timeout property, ScriptControl checks the Allowui property of the object when a time-out occurs. Determines whether user interface elements are allowed to be displayed.

C # background calling foreground and JS method intermodulation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.