Javascript in asp.net interacts with c # in the background,
Recently, I am working on a small project. google maps is embedded in the webpage. I can enter coordinates of longitude and latitude to locate the map position and add a flag. I click the tag to get the remote camera data and play it in the video window. In the actual operation process, the longitude and latitude data and the user name and password data for video login must be extracted from the background database, and the google maps api of the third edition is implemented in javascript, therefore, it is inevitable that the Front-End Script should interact with the background. Because it is implemented in asp.net, the problem evolved into how javascript interacts with c # In asp.net.
C # the code and javaScript Functions call each other in four aspects:
1. How to access the C # function in JavaScript?
2. How to access the C # variable in JavaScript?
3. How to access existing JavaScript variables in C?
4. How to access JavaScript Functions in C?
1. Execute functions in C # code in javaScript Functions:
Method 1: Combine the page and page class
1. function declaration is public
Background code (change public to protected)
public string ss() { return("a"); }
2. You can use <% = ss () %> in html to call // The function name in the C # background.
Foreground script
<Script language = javascript> var a = "<% = ss () %>"; // calls the C # background function alert (a) in JavaScript. </script>
Method 2: JavaScript asynchronous calls are defined on the ASP. Net page.
1. Declare this method as public );
2. Declare this method as a class method (static in C #, Shared in VB. NET), instead of an instance method;
3. Add the WebMethod attribute to this method.
4. Set the EnablePageMethods attribute of the ScriptManager control on the page to true;
5. Use the following JavaScript syntax on the client to call the PAGE method:
PageMethods. [MethodName] (param1, param2,..., callbackFunction );
6. Specify a callback function for the client to call it asynchronously, and accept and process the returned value in the callback function;
7. Add using System. Web. Services;
Example:
Front-end JavaScript code
<Html xmlns = "http://www.w3.org/1999/xhtml">
Background code (. cs file)
Using System; using System. configuration; using System. data; using System. linq; using System. web; using System. web. security; using System. web. UI; using System. web. UI. htmlControls; using System. web. UI. webControls; using System. web. UI. webControls. webParts; using System. xml. linq; using System. web. services; // Add a web service reference public partial class _ Default: System. web. UI. page {protected void Page_Load (object sender, EventArgs e) {} [WebMethod] // indicates the web service method attribute public static string sayhell (string say) // note that the modifier of the function can only be static {return say ;}}
Method 3: JavaScript asynchronous calls are defined in the Web service class.
1. Add a web service to mark this service as allowing ASP. net ajax to call this Web service from the script
The corresponding attribute is [System. Web. Script. Services. ScriptService].
2. Declare the public method and mark it as the [webMethod] attribute method.
3. Add a web Service reference to the ScriptManager control on the page.
<Services> <asp: ServiceReferencePath = "~ /WebService. asmx "/> </Services>
4. Use the following JavaScript syntax on the client to call the web service method:
WebService. HelloWorld ("helloWord", function (res) // Webservice is the web Service Page name.
HelloWord is the method in the web Service Page class, and function is the callback JavaScript function, which mainly processes the returned results.
{
Alert (res );
});
Example:
Page code
<Html xmlns = "http://www.w3.org/1999/xhtml">
Web Service background code
Using System; using System. collections; using System. linq; using System. web; using System. web. services; using System. web. services. protocols; using System. xml. linq; // <summary> /// summary of WebService /// </summary> [WebService (Namespace = "http://tempuri.org/")] [WebServiceBinding (ConformsTo = WsiProfiles. basicProfile1_1)] // to allow ASP. net ajax calls this Web service from the script. Please cancel the comments to the downstream. [System. web. script. services. scriptService] // Add the public class WebService: System. web. services. webService {public WebService () {// If the designed component is used, uncomment the following line // InitializeComponent ();} [WebMethod] // public string HelloWorld (string result) {return result ;}}
Ii. JavaScript accessing C # VARIABLES
Method 1:
A. Hide the field access on the page. You can save the c # variable value in the background to the hidden text field.
<Input id = "xx" type = "hidden" runat = "server">
B. Then, directly obtain the value of the hidden text field in the front-end javascript.
Document. getElementByIdx_x ('xx'). value
Method 2:
A. register the script on the page after assigning values to variables on the server.
Page. RegisterStartScript ("", "<script language = 'javascript '> var vary =" + value + "</script> ");
Value is the background variable, and then the vary value can be directly accessed in javascript. Its value is the value of the background variable value. This method only allows indirect access to the c # variable.
3. Access existing JavaScript variables in C #
Method 1:The foreground uses the server text control to hide the field and write the js variable value into it. The background directly accesses and calls the field through the control id, that is, the background uses Request ["id"] to obtain the value.
Method 2:You can use cookies or sessions to store variable values.
Use the following session code snippets:
. Cs if (Session ["siteName"] = null) // determine whether the Session variable Session with the specified Key value exists ["siteName"] = ""; // create a Session variable if it does not exist // assign a value to the Session ["siteName"] variable. aspx var siteName = "<% = Session [" siteName "] %> ";
IV. C # code execution of JavaScript Functions and JavaScript Functions
Method 1: Use ScriptManager in C. registerStartupScript (this, this. getType (), "edit", "CSharpCallJs ('" + param1 + "', '" + param2 + "')",
Example:
Script Functions
function CSharpCallJs(param1,param2) { alert(param1 + param2); }
Page background code
ScriptManager. registerStartupScript (this, this. getType (), "edit", "CSharpCallJs ('" + param1 + "', '" + param2 + "');", true ); // code for calling the page script function using key code
Method 2: Use the Hidden domain or Literal control to write the values controlled by some js functions into the Hidden domain or Literal control in the foreground, and then use Hidden in the foreground. value or Literal. text reads the foreground value.
The following is a code snippet:
.aspx function GetTitleID(obj) { sTitleID=obj if(sTitleID!=null) document.getElementByIdx_x("HiddenField1").value=type+','+sTitleID; else document.getElementByIdx_x("HiddenField1").value=type+',0'; } .cs string hiddenValue = this.HiddenField1.Value;
Method 3: Page. RegisterStartupScript ("function", "<script> name of the javascript function to be called; </script> ");
The above is how javascript interacts with c # in the background in asp.net. Each situation has a corresponding solution, hoping to help you.