从JavaScript填充选择控制返回空值 [英] Select Control Populated from JavaScript Returns Empty Value

查看:82
本文介绍了从JavaScript填充选择控制返回空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET应用程序中,我有一个服务器端的HTML选择控制。

In my ASP.NET applications, I have a server-side HTML select control.

<select id="CompanyDropDown" runat="server" style="width:330px">
</select>

然后我有我的网页上运行的JavaScript函数填充这个控制,并且还选择了当前项的链接。我可以看到这是工作,因为名单有所有的项目和正确的选择。

I then have a link on my page that runs a JavaScript function that populates this control, and also selects the "current" item. I can see this is working because the list has all the items and the correct one is selected.

然而,当页面回响应按钮的点击。

However, when the page posts back in response to a button click.

<asp:Button runat="server" ID="btnSaveCompany" Text="Save" 
    onclick="btnSaveCompany_Click" />

CompanyDropDown.Value 是空的,它不包含任何项目。我如何能看到回传所选择的价值有什么建议?

CompanyDropDown.Value is empty, and it contains no items. Any suggestions on how I can see the selected value on postback?

(注意:我试图用一个ASP.NET下拉控制,但失败时,控件的页面被渲染后加项目的回发确认)

(Note: I tried using an ASP.NET DropDown control, but that fails postback validation when the control has items that were added after the page was rendered.)

推荐答案

由于项目加入到使用JavaScript的列表不是视图状态,他们不能被检索到服务器端的一部分。如果你只是试图让选定的值,把一个服务器端的隐藏字段在页面上,并使用JavaScript每个下拉的选择改变时其值设置:

Because items added to the list using JavaScript aren't part of the viewstate, they cannot be retrieved server side. If you are only trying to get the selected value, put a server-side hidden field on your page and set its value using JavaScript each time the selection of the drop-down is changed:

jQuery脚本

$('#CompanyDropDown').change(function() {
    $('#inpSelectValue').val($(this).val());
});

隐藏字段标记

<input runat="server" id="inpSelectValue" clientidmode="static" type="hidden" />

隐藏字段的值将背上服务器上后。参考它以检索选定项目的值。一定要添加的ClientIDMode =静态来的下拉以及保持设为您的ASPX页面(指定ID您的控件的呈现ID即 CompanyDropDown ,而不是 parentContainer_CompanyDropDown

The value of the hidden field will be carried to the server on post back. Refer to it to retrieve the value of the selected item. Be sure to add clientidmode="static" to your drop down as well to keep the rendered id of your controls set to the id you assign in the ASPX page (i.e., CompanyDropDown rather than parentContainer_CompanyDropDown):

<select id="CompanyDropDown" runat="server" style="width:330px"
    clientidmode="static" />


另外,你可以使用AJAX来告诉服务器要添加的每个动态生成的列表项或更改选择。我只要这样做,如果你需要维持哪一个被选择另外的项目的列表。


Alternatively, you could use AJAX to tell the server you are adding each dynamically generated list item or changing the selection. I would only do this if you needed to maintain a list of items in addition to which one is selected.

这篇关于从JavaScript填充选择控制返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆