将 Javascript 变量传递给背后的 C# 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14977491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass Javascript Variable To C# Code Behind
提问by TheChampp
How to get value from javascript to C# code behind ? I have an idea with the code below. In javascript code I want to assign the value of "HiddenField" Control with string value and then I want to take this value from "HiddenField" in code behind. But with this code I cannot do it. Can you tell me how to make it ?
如何从 javascript 获取价值到背后的 C# 代码?我对下面的代码有一个想法。在javascript代码中,我想用字符串值分配“HiddenField”控件的值,然后我想从后面的代码中的“HiddenField”中获取这个值。但是使用此代码我无法做到。你能告诉我怎么做吗?
<script>
$(function () {
document.getElementById('HiddenField').value = "active";
console.log(<%= this.HiddenField.Value %>)
});
</script>
<asp:HiddenField ID="HiddenField" runat="server" Value="5" Visible="true" />
回答by Adeel
you need to use ClientID
property of control to get actual element ID in DOM.
您需要使用ClientID
控件属性来获取 DOM 中的实际元素 ID。
<script>
$(function () {
document.getElementById('<%= HiddenField.ClientID%>').value = "active";
console.log(document.getElementById('<%= HiddenField.ClientID%>').value)
});
</script>
<asp:HiddenField ID="HiddenField" runat="server" Value="5" Visible="true" />
回答by Talha
Use the Control IDfor HTML markup that is generated by ASP.NET.
将控件 ID用于由 ASP.NET 生成的 HTML 标记。
document.getElementById('<%= HiddenField.ClientID%>').value = "active";
When a Web server control is rendered as an HTML element, the id attribute of the HTML element is set to the value of the ClientID property. The ClientID value is often used to access the HTML element in client script by using the document.getElementById method.
当 Web 服务器控件呈现为 HTML 元素时,HTML 元素的 id 属性设置为 ClientID 属性的值。ClientID 值通常用于通过使用 document.getElementById 方法访问客户端脚本中的 HTML 元素。
回答by Indra 217
Then send the Hidden value through the javascript function as a variable while calling the controller
然后在调用控制器的同时通过javascript函数将隐藏值作为变量发送
Surely works,
肯定有效,
Cheers Phani*
干杯帕尼*
回答by DeBaum
you may take a look at mshtml As far as I know you call with this C# functions from your javascript code ;-)
你可以看看 mshtml 据我所知,你从你的 javascript 代码中调用了这个 C# 函数;-)