如何从JavaScript调用C#函数?

我想CsharpFunction从JavaScript 调用,在代码隐藏中使用C#函数。我尝试了下面的代码,但是无论JavaScript条件是True还是False,都CsharpFunction被调用了!


JavaScript代码:


if (Javascriptcondition > 0) {

   <%CsharpFunction();%>

}

后面的C#代码:


protected void CsharpFunction()

{

  // Notification.show();

}

如何从JavaScript调用C#函数?


凤凰求蛊
浏览 856回答 3
3回答

catspeake

您可以使用Web方法和Ajax:<script type="text/javascript">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Default.aspx&nbsp; &nbsp;function DeleteKartItems() {&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;url: 'Default.aspx/DeleteItem',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;data: "",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;contentType: "application/json; charset=utf-8",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;success: function (msg) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$("#divResult").html("success");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;error: function (e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$("#divResult").html("Something Wrong.");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;});&nbsp; &nbsp;}</script>[WebMethod]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Default.aspx.cspublic static void DeleteItem(){&nbsp; &nbsp; //Your Logic}

守着星空守着你

.CS File&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; namespace Csharp&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; public void CsharpFunction()&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Code;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; JS code:&nbsp; &nbsp; function JSFunction() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <%#ProjectName.Csharp.CsharpFunction()%> ;&nbsp; &nbsp; }注意:在JS Function中,当调用您的CS页面函数时。。。
打开App,查看更多内容
随时随地看视频慕课网APP