使用JavaScript修改ASP.NET DropDownList时出错 [英] Error when modifying ASP.NET DropDownList with javascript

查看:69
本文介绍了使用JavaScript修改ASP.NET DropDownList时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery更改ASP.NET DropDownList中的项目,但是当我提交表单时,DropDownList的SelectedItem属性为null.知道如何使用jquery修改DropDownList中的项目列表,而不会在后面的代码中引起此错误吗?

I'm changing the items in an ASP.NET DropDownList using jquery, but when I submit the form, the SelectedItem property of the DropDownList is null. Any idea how I can modify the list of items in the DropDownList with jquery without causing this error in the code behind?

这是我设置DropDownList的方式.最初,它是一个空的ASP.NET DropDownList.

Here's the way I'm setting up the DropDownList. Initially, it's an empty ASP.NET DropDownList.

var mailType = $("#ContentPlaceHolder1_ddlMailType");

mailType.empty();
mailType.append("<option></option>");
mailType.append("<option value='D'>Direct Mail</option>");
.
.
.

DropDownList最终会在执行jquery后显示添加的项目.

The DropDownList does end up showing the added items after the jquery executes.

推荐答案

对不起,您不能使用jquery或Javascript将项添加到服务器端ASP.NET Web窗体列表控件中.列表控件的内容存储在ViewState中,除非您做了非常奇怪的事情,否则您的jquery不会更新ViewState.如果启用了验证,则如果表单发布标记/值与ViewState中存储的任何已知值都不匹配,ASP.NET将引发错误.

Sorry, you cannot use jquery or Javascript to add items to a server-side ASP.NET web forms list control. The contents of the list control are stored in ViewState, and unless you've done something very strange, your jquery is not updating the ViewState. If you have validation enabled, ASP.NET will throw an error if the form post tag/value does not match any of the known values that are stored in ViewState.

如果您希望列表框包含在客户端动态添加的项目,请不要使用服务器端控件.只需直接将HTML键入ASP Web表单中即可(不要使用runat = server标记).要在回发时读取控件的内容,请不要引用该控件;而是使用HttpContext.Request.Form ["tag name"]. 请注意,您的代码无法知道jquery已添加到列表框中的内容,因为浏览器发布表单时不会传递此信息-仅传递所选项目的value属性.

If you wish to have listbox with items that are added dynamically on the client side, don't use a server side control. Just type the HTML into the ASP web form directly (don't use the runat=server tag). To read the contents of the control on postback, don't reference the control; instead, use HttpContext.Request.Form["tag name"]. Note that there is no way for your code behind to know what your jquery has added to the list box, as this information is not passed when the browser posts the form-- only the value attribute of the selected item is passed.

有关其他更多信息,请参阅我的其他答案之一

For some more related information, see one of my other answers here.

这篇关于使用JavaScript修改ASP.NET DropDownList时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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