[英]pass parameter to one function in the code behind in C# from javascript
I am trying to pass parameter to one function in the code behind in C# from javascript 我正在尝试将参数从javascript传递给C#背后代码中的一个函数
<script type="text/javascript">
$(document).ready(function () {
$("#some_id").click(function () {
var id = document.getElementById('HiddenField2');
var a = <%=btn_Click(id)%>;
});
});
</script>
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "item_id")%>' />
code behind
public string btn_Click(String item_id)
{
/*do some thing*/
return null;
}
But this piece of code always giving me error of context. 但是这段代码总是给我上下文错误。 That id is not defined in this context. 在此上下文中未定义该ID。 Can some please let me know what wrong i am doing? 可以让我知道我在做什么错吗?
First, var id
is javascript and the code within <%= %>
is C#. 首先, var id
是javascript, <%= %>
的代码是C#。 You can't pass a variable between the languages like that. 您不能在像这样的语言之间传递变量。
Second, the value of id
in this case is going to be a DOM element which C# can't use anyways. 其次,在这种情况下, id
的值将是C#不能使用的DOM元素。 If you want to get the value of HiddenField2 within the code behind you can use HiddenField2.Value
. 如果要在后面的代码中获取HiddenField2的值,则可以使用HiddenField2.Value
。
Third, since you're using ASP.net, instead of using jQuery's .click
handler you should use the onServerClick
attribute to wire up the button click behavior to btn_Click
. 第三,由于你使用ASP.net,而不是使用jQuery的.click
处理程序,你应该使用onServerClick
属性要连接按钮点击行为btn_Click
。
The button click event in C# will be triggered by Postback when your browser post data back to asp.net I do not understand why you use HiddenField here,so my suggestion do not consider about it 当您的浏览器将数据发回到asp.net时,C#中的按钮单击事件将由Postback触发。我不明白您为什么在这里使用HiddenField,所以我的建议不考虑
Solution 1: first you can extract your code in btn_Click to a HttpHandler(*.ashx in asp.net),then use Ajax by using js framework like jQuery to send data to your HttpHandler,data returned by HttpHandler can be processed by js 解决方案1:首先可以将btn_Click中的代码提取到HttpHandler(asp.net中的* .ashx),然后使用jQuery之类的js框架将Ajax发送到HttpHandler,由HttpHandler返回的数据可以由js处理
Solution 2: if your code in btn_Click is relevent to your page, just use ajax Get method, the data will send to your page,the data returned by your data will be processed by js too 解决方案2:如果您在btn_Click中的代码与您的页面无关,只需使用ajax Get方法,数据将发送到您的页面,您的数据返回的数据也将由js处理
In the end, if you are new to web, I recommend you to learn or implement asp.net MVC, in my opinion, it is more flexible than asp.net webform 最后,如果您不熟悉Web,我建议您学习或实现asp.net MVC,我认为它比asp.net Webform更加灵活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.