简体   繁体   English

使用参数从JavaScript调用CodeBehind方法

[英]Call CodeBehind Method from JavaScript with parameter

I'm trying to call a code behind method from JavaScript code. 我正在尝试从JavaScript代码中调用方法后面的代码。 This works fine, but I am not sure how can I pass a JavaScript parameter to the method. 这可以正常工作,但是我不确定如何将JavaScript参数传递给该方法。 If I put any value between the parenthesis, it is related as a CodeBehind context rather then script context. 如果我在括号之间放置任何值,则它将作为CodeBehind上下文而不是脚本上下文相关。 What is the solution to pass this parameter? 传递此参数的解决方案是什么?

JavaScript: JavaScript:

var arg = this.id
<% setSelection(arg); %>   

C#: C#:

[WebMethod]
public void setSelection(string productID)
{
   Session["selection"] = productID
}

I get this error of course: CS0103: The name 'arg' does not exist in the current context 我当然收到此错误:CS0103:名称“ arg”在当前上下文中不存在

Your setSelection(arg) call is not calling the code behind from JavaScript. 您的setSelection(arg)调用未从JavaScript调用代码。 It is getting called on the server side, before the HTML response is even output to the browser, way before the JavaScript executes. 在HTML响应甚至没有输出到浏览器之前,即在执行JavaScript之前,就在服务器端被调用。 Also the arg is treated as a C# variable. arg也被视为C#变量。

If you want to make the call from JavaScript, you need to use AJAX. 如果要通过JavaScript进行调用,则需要使用AJAX。 See this example . 请参阅此示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM