javascript 在后面的代码中使用javascript变量分配C#变量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18977804/
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
Assigning C# variable value using javascript variable in code behind
提问by ankita alung
I am trying to access the script variable pic
and assign it to another variable in C#, say hidden field hdn
. The script below is also placed on the same code behind page for some reason. I can directly access the hidden field here. But how do I assign it value from the script variable?
我正在尝试访问脚本变量pic
并将其分配给 C# 中的另一个变量,例如 hidden field hdn
。由于某种原因,下面的脚本也被放置在相同的代码隐藏页面上。我可以在这里直接访问隐藏字段。但是如何从脚本变量中为其赋值?
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
alert(pic);
});
});
});
</script>
回答by MichaC
There is no way to assign a C# variable by javascript. You have to send that value from the client (where you JavaScript is running) to the Server, and assign it. This is so called ajax request, just google it and you'll find millions of good examples of how to achieve that.
无法通过 javascript 分配 C# 变量。您必须将该值从客户端(运行 JavaScript 的地方)发送到服务器,并分配它。这就是所谓的 ajax 请求,只要用谷歌搜索一下,你就会找到数百万个如何实现它的好例子。
回答by MichaC
create a hidden filed and then set the value from javascript
创建一个隐藏的文件,然后从 javascript 设置值
<asp:hiddenfield id="hf_MyValue"
value="whatever"
runat="server"/>
How To Set value in javascript
如何在javascript中设置值
//get value from hidden filed
var test= document.getElementById('<%= hf_MyValue.ClientID %>');
//set value in hidden filed
document.getElementById('<%= hfBrand.ClientID %>').value = "True";
回答by Alvin Jones
Create a hidden variable like this,
创建一个像这样的隐藏变量,
<input type="hidden" id="hdnVariable" runat="server" />
Now try this code
现在试试这个代码
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
//assign value to server side hidden variable
$("#<%=hdnVariable.ClientID%>").val(pic);
});
});
});
</script>
Now you can access this hidden field from C# code like this
现在您可以像这样从 C# 代码访问这个隐藏字段
string pic=hdnVariable.Value;