[英]How to call COM Interop of an C# Class,methods using javascript
我創建了一個C#類的COM互操作,以使用JavaScript來訪問此互操作。 該類包含一個Addition()方法,但是該方法無法在javascript中訪問。
代碼如下
接口IMathInterface
namespace CCWTEST
{
[Guid("756892A0-1242-4BF7-984D-C13E68000E8E")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IMathInterface
{
[DispId(1)]
int Addition(int i, int j);
}
}
類ClassMath
[Guid("CA9AD3A7-BD31-4BE2-A780-8864D493BA5F")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("CCWTEST.ClassMath")]
public class ClassMath : IMathInterface
{
[ComVisible(true)]
public int Addition(int x, int y)
{
return x + y;
}
}
然后創建的snk文件CCWMathTest.snk
也注冊到GACUtil中。 然后使用RegAsm命令創建一個tlb文件。所有這些操作均成功完成。
然后創建一個Web應用程序以將類方法訪問javascript。
碼
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!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">
<object classid="CLSID:CA9AD3A7-BD31-4BE2-A780-8864D493BA5F" height="0" width="0"
id="obj7" name="obj7">
</object>
<title></title>
<script type="text/javascript">
window.onload = onLoad;
function onLoad() {
alert(obj7.Addition(3,1));
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
在運行此代碼時,它給我一個錯誤“對象不支持屬性或方法'添加'”我如何使用COM互操作在Javascript中訪問此方法
你為什么用javascript調用它? 在頁面上創建一個WebMethod,該WebMethod調用COM對象,然后通過javascript通過AJAX調用此方法。 像這樣:
//server side
[WebMethod]
public static string DoSomething()
{
//call COM
return "something";
}
//client side
$.ajax({
type: "POST",
url: "page.aspx/DoSomething",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.