asp.net javascript and background C # interaction _ Practical Skills

Source: Internet
Author: User
Tags instance method

Recently done a small project, the Web page embedded in Google Maps, the input latitude and longitude coordinates can locate map location and add tags, click on the tag to obtain remote camera data and in the video window to achieve playback. In the actual operation process, due to the longitude and latitude data and video login username password data are extracted from the background database, and the third version of the Google Maps API is implemented in JavaScript, it is inevitable that the front-end script to interact with the background. Because it was implemented in ASP.net, the problem evolved into how JavaScript in asp.net interacts with background C #.

There are four main ways in which C # code interacts with JavaScript functions:

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 #?

Executing functions in C # code in a JavaScript function:
method One: page and Page class combination
1. function declared as public

Background code (change public to protected also can)

 public string SS ()

    {return

    ("a");

    }

2, in the HTML with <%=SS ()%> can call//is in C # background function name

Foreground script

 <script language=javascript>

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

    alert (a)

    in C # background in//javascript; </script> 


Method Two: JavaScript asynchronous call the method defined in the ASP.net page
1. Declare the method to be publicly owned (public);
2. Declare the method as a class method (Static,vb in C #. NET, rather than the instance method;
3. Add the method to the "WebMethod" property
4. Set the Enablepagemethods property of the ScriptManager control on the page to true;
5. Call the page method on the client using the following JavaScript syntax
Pagemethods. [MethodName]   (Param1,param2,..., callbackfunction);
6. Asynchronously invokes the specified callback function for the client, accepting the return value in the callback function and further processing;
7. Add using System.Web.Services;

Example:

Foreground JavaScript code

 
 

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 Web service references public

partial class _default:system.web.ui.page
{
 protected void Page_Load (object sender, EventArgs e)
 {
  

 }
 [webmethod]//marked as Web service method property public
 static string Sayhell (string say)//note modifier of function, only static {return
  say
 }
}

Method Three: JavaScript asynchronous calls the methods defined in the Web service class

1. Add a Web service to mark the service to allow the use of ASP.net AJAX to invoke this Web service from script

The corresponding property is [System.Web.Script.Services.ScriptService]

2. Declare the method public and mark the method as a [WebMethod] property method
3. ScriptManager the control on the page and add the Web service reference

<services><asp:servicereferencepath= "~/webservice.asmx"/></services>

4. Invoke the Web service method on the client using the following JavaScript syntax

Webservice.helloworld ("Helloword", Function (res)//webservice is the Web service page name

Helloword is a method in the Web Services page class, and function is a callback JavaScript function that handles the returned results primarily
{
Alert (res);
});

Example:

Page code

  

Web Services 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>
///webservice's summary description
///</summary>
[WebService (Namespace = "http:// tempuri.org/")]
[webservicebinding (ConformsTo = wsiprofiles.basicprofile1_1)]
//To allow use of ASP.net AJAX Call this Web service from the script, uncomment the line. 
 [system.web.script.services.scriptservice]//Note To add the Mark public
class WebService: System.Web.Services.WebService {public

 WebService () {

  //If you are using a design component, uncomment the following line 
  //initializecomponent ( ); 
 }

 [The webmethod]//method is to be marked with the attribute public
 string HelloWorld (string result) {return result
 }
 
}

Second, JavaScript access to C # variables
Method One:
A, hidden field access through the page, you can save the C # variable values in the background in the hidden text field.

<input id= "xx" type= "hidden" runat= "Server" >
b, and then take the value of the hidden text field directly in the foreground JavaScript.
document.getelementbyidx_x (' xx '). Value

Method Two:
A, register the script on the page after the server-side variable is assigned
Page.registerstartscript ("", "<script language= ' JavaScript ' >var vary=" + value + "</script>");
Value is a background variable, and then JavaScript can directly access the vary value, which is the value of the backend variable value, which is simply an indirect way to access C # variables.
existing variables to access JavaScript in C #
Method One: the foreground uses the server text control to hide the field, writes the JS variable value to it; the background is accessed and invoked directly through the control ID, that is, the background uses request["id" to get the value.

method Two: can use cookie or session to store variable value, the background directly use
Use session following is a code fragment:

. cs If 
(session["siteName"] = = NULL)//Determine if there is a session variable that specifies a key value 
session["siteName"] = "";//If not present create session variable 
//Assign value to session["siteName" variable 
. aspx 
var sitename= "<%=session[" SiteName "%>";

IV. C # code executes JavaScript functions and invokes JavaScript functions
method One: C # uses Scriptmanager.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);/key code calls the code for the page script function

Method Two: Use the hidden field or literal control, in the foreground use JS script to put some JS function control value into the hidden field or literal control, then the foreground uses Hidden.value or literal.text to read foreground value.
The following is a code fragment:

 . 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 Three: Page.registerstartupscript ("function", "<script> the JavaScript function name you want to invoke;</script>");

The above is the asp.net JavaScript and Backstage C # interaction method, each situation has a corresponding solution, hope to be able to help everyone.

Related Article

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.