Compile the js file into dll methods for the page to call

  • 2020-12-26 05:38:35
  • OfStack

1. Add one project to the solution: JSControl

2. Add 1 js file to this project (JScript1.js)

The contents of the script:


function showAlert(){
alert('Today is a good dary');
}

3. Change the attribute of JScript1.js, Build Action is Embedded Resource (embedded resource)

4. Add a line to the AssemblyInfo.cs file for the JSControl project :(note that JSControl.JScript1.js, JSControl is the namespace and JScript1.js is the filename)


[assembly: System.Web.UI.WebResource("JSControl.JScript1.js", "application/x-javascript")]

5. Add 1 class to register client script in the project:


namespace JSControl
{
public class Class1 : System.Web.UI.WebControls.WebControl
{
protected override void OnPreRender(EventArgs e)
{
if (this.Page != null)
{
ClientScriptManager manager = this.Page.ClientScript;
manager.RegisterClientScriptResource(typeof(Class1), "JSControl.JScript1.js");
}
base.OnPreRender(e);
}
}
}

6. Add a reference to JSControl.dll in the project calling js

7. Register JSControl.dll for the page where the script is to be invoked


<%@ Register Assembly="JSControl" Namespace="JSControl" TagPrefix="zhi" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<zhi:Class1 ID="rs1" runat ="server"/>
</head>

8. Call


<script type="text/javascript">
$(function ()
{
showAlert();
});
</script>

Related articles: