后台动态生成静态select标签的option项

以下为代码示例:

<select id="Category_<%#Eval("BTUserID") %>" name="Category_<%#Eval("BTUserID") %>" disabled on onchange=setHourlyCost("<%#Eval("BTUserID") %>") style="width:200px">
         <option value="0">User-Defined</option>
         <%=GetOptions4Arr() %>  /*动态为select添加option*/
</select>

全局变量:

 List<PCS.DAL.EF.Category> CategoryList = PCS.DAL.EF.Repository.GetInstance().GetCategoryList();
List<PCS.DAL.EF.v_BTUser_Category> V_BTUser_Category = PCS.DAL.EF.Repository.GetInstance().GetUserCategory();
static List<PCS.DAL.EF.v_BTUser_Category> SourceComparer = new List<PCS.DAL.EF.v_BTUser_Category>(); int SourceIndex = 0;

实现方法:


public void GetOrderedSource()//对数据源进行排序
{
var orderList = from l in V_BTUser_Category
orderby l.btuserfirstname, l.btuserlastname
select l;
SourceComparer = orderList.ToList();
}


public
string GetOptions4Arr() { var btUserList = (from l in SourceComparer orderby l.btuserfirstname, l.btuserlastname select l).ToList() ; var orderList = from c in CategoryList orderby c.Category1 select c; List<PCS.DAL.EF.Category> myList = orderList.ToList();/*以上为数据源部分,您可以做出相应的修改*/ string options=""; if (btUserList.Count > 0) { int categoryID = Convert.ToInt32(btUserList[SourceIndex].CategoryID);//此处取远数据的CategoryID值 for (int i = 0; i < myList.Count; i++) {
            //此处可以换成您想展示的数据 options
+= "<OPTION value='" + myList[i].CategoryID + "' title='" + myList[i].HourlyCost + "' id='" + myList[i].BillingRate + "'"; if (categoryID == myList[i].CategoryID)//此处判断源数据()与展示数据的相等ID项,若相等则选中,否则不指定selected属性 options += " selected='selected'"; options += ">" + myList[i].Category1 + "</OPTION>"; } if (SourceIndex < btUserList.Count) SourceIndex++; else SourceIndex = 0; } return options; }

效果图:

 

注意看此处的option项:

会动态地添加value属性,title属性,id属性,且此三属性均绑定了数据库中的字段值,这样做是为了使用JS代码来对下拉控件做选择时,将hourlycost和billingrate俩对应行的值进行变更。

 

下面贴出JS代码:

function setHourlyCost(id)
        {
            var e=document.getElementById("HourlyCost_"+id);
            var temp=document.getElementById("Category_"+id);
            var eb=document.getElementById("BillingRate_"+id);
            if (temp.value=="0")
            {
       
                e.readOnly=false;
                e.style.backgroundColor="white"
                e.value=""
        
                eb.readOnly=false;
                eb.style.backgroundColor="white"
                eb.value=""
            }
            else
            {
                e.readOnly=true;
                e.style.backgroundColor="lightgrey"
                e.value=temp[temp.selectedIndex].title;/*将title属性值赋值给hourlycost控件的value属性*/
     
                eb.readOnly=true;
                eb.style.backgroundColor="lightgrey"
                eb.value=temp[temp.selectedIndex].id;/*将id属性值赋值给billingrate控件的value属性*/
    
            }
 
        }

 

posted @ 2014-05-19 11:14  _嘻嘻哈哈_  阅读(373)  评论(0编辑  收藏  举报