且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JavaScript来设置隐藏字段的值,然后从服务器端的C#代码访问值

更新时间:2023-02-11 22:29:41

我会做这样的:首先,删除 RUNAT =服务器从隐藏字段属性:

 <输入类型=隐藏ID =accomodationAnswer/> 

现在,服务器,要读取值上,这样做:



 字符串accomodationAnswer =的Request.Form [accomodationAnswer]; 

//现在用的,而不是accomodationAnswer.Value
//在您指定使用的是
,C#代码accomodationAnswer

这应该这样做。


I am using a nested html unordered list styled as a drop down. When the a tag within the inner lists list item is clicked it trigger some javascript which is supposed to set the value of a hidden field to the text for the link that was clicked.

The javascript seems to work - I used an alert to read the value from the hidden field but then when I try to put that value in the querystring in my asp.net c# code behind - it pulls the initial value - not the javascript set value.

I guess this is because the javascript is client side not server side but has anyone any idea how i can get this working

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# code

String qstr = "accom=" + getValFromLiId(accomodationAnswer.Value) + "&sleeps=" + getValFromLiId(sleepsAnswer.Value) + "&nights=" + getValFromLiId(nightsAnswer.Value) + "&region=" +
getValFromLiId(regionAnswer.Value) + "&price=" + Utilities.removeCurrencyFormatting(priceAnswer.Value);

I would do this: First, remove the runat='server' attribute from the hidden field:

<input type="hidden" ID="accomodationAnswer" />

Now, on the server, where you want to read that value, do this:

string accomodationAnswer = Request.Form["accomodationAnswer"];

// now use accomodationAnswer instead of accomodationAnswer.Value 
// in the C# code that you indicated you are using

That should do it.