asp. javascript in net interacts with background c

  • 2021-07-06 10:48:40
  • OfStack

Recently, I did a small project. google maps was embedded in the webpage. Enter latitude and longitude coordinates to locate the map position and mark it. Click the mark to obtain the remote camera data and play it in the video window. In the actual operation process, because the latitude and longitude data and the user name and password data of video login are extracted from the background database, and the third version of google maps api is implemented in javascript, it is inevitable that the front-end script interacts with the background. Because it is implemented in asp. net, the problem evolves into how javascript in asp. net interacts with c # in the background.

There are four main aspects to the mutual call between C # code and javaScript function:

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 the JavaScript function in C #?

1. Execute the functions in the C # code in the javaScript function:
Method 1: Combine pages with page classes
1. The function is declared as public

Background code (public can be changed to protected)


 public string ss()

    {

    return("a");

    }

2. Used in html < %=ss()% > Can call//is the background function name in C #

Foreground script


 <script language=javascript>

    var a = "<%=ss()%>";//JavaScript Call in C# Background function 

    alert(a);

    </script> 


Method 2: JavaScript asynchronously calls the method defined in the ASP. Net page
1. Declare the method as public (public);
2. Declare the method as a class method (static in C #, Shared in VB. NET) instead of an instance method;
3. Add the "WebMethod" attribute to the method
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. Specify a callback function for client asynchronous call, accept the return value in the callback function and process it in one step;
7. Add using System. Web. Services;

Example:

Foreground JavaScript code


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title> Untitled page </title>

 <script type="text/javascript">
 function JsCallCSharp(param1)
 {   
  PageMethods.sayhell(param1,onSayHelloSucceeded);//sayhell It is marked in the background. " webMethod "Method of property  param1 Is the parameter passed into the method, onSayHelloSucceeded Is the callback function is mainly for the results returned in the background 1 Step processing 
 }  
 function onSayHelloSucceeded(result)// Bound callback function  
 { 
 alert(result);
 } 

 </script>

</head>
<body>
 <form id="form1" runat="server">
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">//ScriptManager Control management script, pay attention to setting EnablePageMethods="true" This property 
 </asp:ScriptManager>
 <div>
  <input type="button" onclick="JsCallCSharp('hello')" />
 </div>
 </form>
</body>
</html>

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 reference 

public partial class _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
  

 }
 [WebMethod]// Mark as web Service method properties 
 public static string sayhell(string say)// Note the modifiers of functions , Can only be static 
 {
  return say;
 }
}

Method 3: JavaScript asynchronously calls the methods defined in the Web service class

1. Add an web service to label the service as allowing this Web service to be invoked from a script using ASP. NET AJAX

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

2. Declare the method public and label it as the [webMethod] attribute method
3. ScriptManager control in page and add 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 service page class, and function is a callback JavaScript function is mainly used to process the returned results
{
alert(res);
});

Example:

Page code


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title> Untitled page </title>

 <script type="text/javascript">
 function JsCallCSharp(param1)
 {   
  PageMethods.sayhell(param1,onSayHelloSucceeded);
 }  
 function onSayHelloSucceeded(result)
 { 
 alert(result);
 } 

// This method is the called function 
 function JsCallWebService()
 {
  WebService.HelloWorld("helloWord",function(res)// Call web Services 
  {
  alert(res);
  });
 }
 </script>

</head>
<body>
 <form id="form1" runat="server">
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" >
 <Services><asp:ServiceReference Path="~/WebService.asmx" /></Services>// Be careful to reference web Services 
 </asp:ScriptManager>
 <div>
  <input type="button" onclick="JsCallCSharp('hello')" value=" Test C# Background page " />
  <input type="button" onclick="JsCallWebService()" value=" Test web Background class " />
 </div>
 </form>
</body>
</html>

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>
///WebService  Summary description of 
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow the use of  ASP.NET AJAX  Invoke this from a script  Web  Service, please uncomment on the following link.  
 [System.Web.Script.Services.ScriptService]// Note to add this label 
public class WebService : System.Web.Services.WebService {

 public WebService () {

  // If you use a designed component, uncomment the following line  
  //InitializeComponent(); 
 }

 [WebMethod]// The property to be marked by the method 
 public string HelloWorld(string result) {
  return result;
 }
 
}

2. JavaScript Access C # Variable
Method 1:
a, accessed through hidden fields on the page, can save c # variable values to hidden text fields in the background.

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

Method 2:
a, register the script on the page after the server-side variable assignment
Page. RegisterStartScript ("," < script language='javascript' > var vary=" + value + " < /script > ");
value is the background variable, and then the value of vary can be directly accessed in javascript, and its value is the value of the background variable value, which is only an indirect way to access c # variable.
3. Existing variables accessing JavaScript in C #
Method 1: The foreground uses the server text control to hide the field and writes the js variable value into it; The background accesses and calls directly through the control id, i.e. the background uses Request ["id"] to get the value.

Method 2: You can use cookie or session to store variable values, and use them directly in the background
Using session, the following is a code snippet:


.cs 
if (Session["siteName"] == null)// Determines whether the specified Key Value of Session Variable  
Session["siteName"] = "";// If it does not exist, create Session Variable  
// To Session["siteName"] Variable assignment  
.aspx 
var siteName="<%=Session["siteName"] %>";

4. The C # code executes the JavaScript function and calls the JavaScript function
Method 1: ScriptManager. RegisterStartupScript (this, this. GetType (), "edit", "CSharpCallJs ('" + param1 + "', '" + param2 + "')" is used in C #.

Example:

Script function


function CSharpCallJs(param1,param2) 
  { 
   alert(param1 + param2); 
  } 

Page background code


ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "CSharpCallJs('" + param1 + "','" + param2 + "');", true);// Key code the code that calls the page script function 

Method 2: Use a hidden field or an Literal control, use an js script in the foreground to write some values controlled by an js function into the hidden field or an Literal control, and then use Hidden. Value or Literal. Text in the foreground to read the foreground values.
Here is the 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 > The name of the javascript function you want to call; < /script > ");

The above is the interaction method between javascript in asp. net and c # in the background. There are corresponding solutions in each case, hoping to help everyone.


Related articles: