欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net mvc下拉框Html.DropDownList 和DropDownListFor的常用方法

程序员文章站 2024-02-20 21:50:22
一、非强类型: controller: viewdata["areid"] = from a in rp.getarea()    &n...

一、非强类型:

controller:
viewdata["areid"] = from a in rp.getarea()
                               select new selectlistitem {
                               text=a.areaname,
                               value=a.areaid.tostring()
                               };
view:
@html.dropdownlist("areid")

还可以给其加上一个默认选项:@html.dropdownlist("areid", "请选择");

二、强类型:

dropdownlistfor常用的是两个参数的重载,第一参数是生成的select的名称,第二个参数是数据,用于将绑定数据源至dropdownlistfor

modle:

   public class settingsviewmodel
   {
       repository rp =new repository();
       public string listname { get; set; } 
       public  ienumerable<selectlistitem> getselectlist()
       {
               var selectlist = rp.getarea().select(a => new selectlistitem {
                               text=a.areaname,
                               value=a.areaid.tostring()
                               });
               return selectlist;
           }
       }

controller:
       public actionresult index()
       {
           return view(new settingsviewmodel());
       }

view:
@model mvc3applicationtest2.models.settingsviewmodel
@html.dropdownlistfor(m=>m.listname,model.getselectlist(),"请选择")