简体   繁体   English

用c#声明javascript变量

[英]Declaring javascript variable with c#

I have a DropDownList and I am looking to use the Text of the selected index, in a Javascript String, by declaring it within a hiddenfield and then declaring through C# so that the Javascript variable is not cleared when the page reloads. 我有一个DropDownList,我希望在Javascript字符串中使用所选索引的文本,在隐藏字段中声明它,然后通过C#声明,以便在页面重新加载时不清除Javascript变量。

I would love some advice on whether hiddenfields are correct idea, and also how to declare the hiddenfield value as a Javascrpt variable. 我想知道一些关于隐藏字段是否正确的建议,以及如何将隐藏字段值声明为Javascrpt变量。

<asp:DropDownList runat="server" ID="dropCallbackReason" SelectedIndexChanged="riskSeverityDropDown_SelectedIndexChanged" onChange="javascript:updateCallBackReason()" ClientIDMode="Static" >
       <asp:ListItem Text="-- Select Reason --" Value="1"></asp:ListItem>
       <asp:ListItem Text="Booking" Value="6"></asp:ListItem>
       <asp:ListItem Text="Discussing" Value="11"></asp:ListItem>
       <asp:ListItem Text="Contract" Value="45"></asp:ListItem>
</asp:DropDownList>
<asp:HiddenField id="ValueHiddenField" value="" runat="server"/>

<script type="text/javascript">
      function updateCallBackReason() {
      var ddlReason = document.getElementById("<%=dropCallbackReason.ClientID%>");
      callBackReasonPreSring = ddlReason.options[ddlReason.selectedIndex].text;
      callBackReason = callBackReasonPreSring.replace(/ /g, '');
      return callBackReason;
      }
      $(document).ready(function () { updateCallBackReason() });
 </script>

Many Thanks, 非常感谢,

Using a hidden field is not unusual. 使用隐藏字段并不罕见。 I don't see where you are writing to it in your code though. 我不会在你的代码中看到你在哪里写它。

Your best option is to store your values in a Session instead of hidden field. 您最好的选择是将值存储在Session而不是隐藏字段中。 It's much cleaner approach. 这是更清洁的方法。

You can do it in 2 ways, server side or client side. 您可以通过两种方式完成此操作,即服务器端或客户端。

As for server side Session , it's pretty straightforward while client side Session is not usual and you will need to use external libraries like this one here: https://github.com/AlexChittock/JQuery-Session-Plugin 至于服务器端Session ,它非常简单,而客户端Session并不常见,你需要在这里使用像这样的外部库: https//github.com/AlexChittock/JQuery-Session-Plugin

Another option is to use Cookies . 另一种选择是使用Cookies

//Set cookie
$.cookie("somevar", "5");

// Get cookie
$.cookie("somevar")

//Delete cookie
$.cookie("somevar", null);

Hope this helps. 希望这可以帮助。

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

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