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

man*_*yst 4 javascript c#

我使用嵌套的html无序列表作为下拉列表.当单击内部列表列表项中的a标记时,它会触发一些javascript,该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" />
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

C#代码

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

Jas*_*ing 12

我会这样做:首先,runat='server'从隐藏字段中删除属性:

<input type="hidden" ID="accomodationAnswer" />
Run Code Online (Sandbox Code Playgroud)

现在,在要读取该值的服务器上,执行以下操作:

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

// now use accomodationAnswer instead of accomodationAnswer.Value 
// in the C# code that you indicated you are using
Run Code Online (Sandbox Code Playgroud)

应该这样做.


小智 6

试试这个

如果您使用.net 4.0然后在页眉中.

Language ="C#"AutoEventWireup ="true"CodeFile ="Page.cs"Inherits ="Page"

随着这个写:

ClientIDMode="Static"
Run Code Online (Sandbox Code Playgroud)

它有助于在运行时不更改服务器端控件ID

现在

将javascript中的值设置为

document.getElementById("hiddenField").value ="Vallue";

并在下面的代码隐藏中访问.

string hiddenVallue = hiddenField.Value.ToString();