![](/img/trans.png)
[英]how to set asp.net hidden field in javascript and access the value in c# code behind
[英]Using javascript to set value of hidden field then access value from serverside c# code
我正在使用樣式為下拉列表的嵌套 html 無序列表。 當點擊內部列表列表項中的 a 標簽時,它會觸發一些 javascript,它應該將隱藏字段的值設置為被點擊的鏈接的文本。
javascript 似乎工作 - 我使用警報從隱藏字段中讀取值但是然后當我嘗試將該值放入我的 asp.net c# 代碼中的查詢字符串中時 - 它提取初始值 - 而不是 javascript 設置值.
我想這是因為 javascript 是客戶端而不是服務器端,但有人知道我如何讓它工作
HTML
<div class="dropDown accomodation">
<label for="accomodationList">Type of accomodation</label>
<ul class="quicklinks" id="accomodationList">
<li><a href="#" title="Quicklinks" id="accomodationSelectList">All types
<!--[if IE 7]><!--></a><!--<![endif]-->
<!--[if lte IE 6]><table><tr><td><![endif]-->
<ul id="sub" onclick="dropDownSelected(event,'accomodation');">
<li><a href="#" id="val=-1$#$All types" >All types</a></li>
<li><a href="#" id="val=1$#$Villa" >Villa</a></li>
<li><a href="#" id="val=2$#$Studio" >Studio</a></li>
<li><a href="#" id="val=3$#$Apartment" >Apartment</a></li>
<li><a class="last" href="#" id="val=4$#$Rustic Properties" >Rustic Properties</a></li>
</ul>
<!--[if lte IE 6]></td></tr></table></a><![endif]-->
</li></ul>
</div>
<input type="hidden" ID="accomodationAnswer" runat="server" />
javascript
if(isChildOf(document.getElementById(parentList),document.getElementById(targ.id)) == true)
{
document.getElementById(parentLi).innerHTML = tname;
document.getElementById(hiddenFormFieldName).Value = targ.id;
alert('selected id is ' + targ.id + ' value in hidden field is ' + document.getElementById(hiddenFormFieldName).Value);
}
C# 代碼
String qstr = "accom=" + getValFromLiId(accomodationAnswer.Value) + "&sleeps=" + getValFromLiId(sleepsAnswer.Value) + "&nights=" + getValFromLiId(nightsAnswer.Value) + "®ion=" +
getValFromLiId(regionAnswer.Value) + "&price=" + Utilities.removeCurrencyFormatting(priceAnswer.Value);
我會這樣做:首先,從隱藏字段(體內)中刪除runat='server'
屬性:
<input type="hidden" id="accomodationAnswer" />
現在,在要讀取該值的服務器上,執行以下操作:
string accomodationAnswer = Request.Form["accomodationAnswer"];
// now use accomodationAnswer instead of accomodationAnswer.Value
// in the C# code that you indicated you are using
那應該這樣做。
嘗試這個
如果您使用的是 .net 4.0,則在頁眉中。
Language="C#" AutoEventWireup="true" CodeFile="Page.cs" Inherits="Page"
連同這篇寫:
ClientIDMode="Static"
它有助於在運行時不更改服務器端控件 ID
現在
將 javascript 中的值設置為
document.getElementById("hiddenField").value = "Value";
並在代碼隱藏中訪問,如下所示。
字符串 hiddenValue=hiddenField.Value.ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.