如何使用jQuery在Formview中设置Dropdownlist的值

时间:2014-01-13 06:07:35

标签: jquery asp.net formview

我在asp.net formview中有一些asp文本框和asp下拉列表。我可以使用jQuery来设置城市文本框的值:

$('#<%=fvSubscriber.FindControl("txtMailingAddrCity").ClientID %>').val('Anchorage');

但是,当我尝试使用以下命令设置状态下拉列表的值时:

$('#<%=fvSubscriber.FindControl("ddlMailingState").ClientID %>').val('AK');

我收到一个空引用异常。我哪里错了?

更新:这是标记

<label class="labelWidth40" for="txtMailingAddrCity">
    City:
</label>
<asp:TextBox ID="txtMailingAddrCity" CssClass="alpha" runat="server"
        Text='<%# Eval("mailingCity") %>' MaxLength="50" OnTextChanged="ValueChanged" TabIndex="2" />
<label class="labelWidth50" for="ddlMailingState">
    State:
</label>
<asp:DropDownList ID="ddlMailingState" CssClass="stateDDL" runat="server" OnSelectedIndexChanged="ValueChanged" TabIndex="2" />

2 个答案:

答案 0 :(得分:0)

也许您在find上遇到问题,请尝试使用控件上的静态ID:

<asp:DropDownList ID="ddlMailingState" CssClass="stateDDL" runat="server"  ClientIDMode="Static" OnSelectedIndexChanged="ValueChanged" TabIndex="2"/>

<asp:TextBox ID="txtMailingAddrCity" CssClass="alpha" runat="server" ClientIDMode="Static"
    Text='<%# Eval("mailingCity") %>' MaxLength="50" OnTextChanged="ValueChanged" TabIndex="2"/>

直接在jQuery上设置:

$("#ddlMailingState").val("AK");
$("#txtMailingAddrCity").val("Anchorage");

答案 1 :(得分:0)

异常可能来自空数据源(我在测试中发现的)。您需要添加EmptyDataTemplete,如下所示:

<EmptyDataTemplate>
    <label class="labelWidth40" for="txtMailingAddrCity">
        City:
    </label>
    <asp:TextBox ID="txtMailingAddrCity" CssClass="alpha" runat="server"
        Text="" MaxLength="50" OnTextChanged="ValueChanged" TabIndex="2" />
    <label class="labelWidth50" for="ddlMailingState">
        State:
    </label>
    <asp:DropDownList ID="ddlMailingState" CssClass="stateDDL" runat="server" OnSelectedIndexChanged="ValueChanged" TabIndex="2" />
</EmptyDataTemplate>