【问题标题】:make dropdown list of person制作人的下拉列表
【发布时间】:2011-09-28 00:43:11
【问题描述】:

我有一个模型:

public  class person
 {
   public int id{get;set;}
   public string name{get;set;}
 }

如何通过以下语法从 mvc3 razor 中的人员列表中创建一个下拉列表:@Html.DropDownListFor(...)? 我的人员列表必须是什么类型?

对不起,我是 mvc3 的新手

谢谢大家

【问题讨论】:

标签: asp.net-mvc-3


【解决方案1】:
    public class PersonModel
    {           
        public int SelectedPersonId { get; set; }
        public IEnumerable<Person> persons{ get; set; }
    }
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

然后在控制器中

public ActionResult Index()
{        
    var model = new PersonModel{             
        persons= Enumerable.Range(1,10).Select(x=>new Person{

            Id=(x+1),
            Name="Person"+(x+1)                
        }).ToList()                     <--- here is the edit

    };
    return View(model);//make a strongly typed view
}

你的视图应该是这样的

@model Namespace.Models.PersonModel
<div>
   @Html.DropDownListFor(x=>x.SelectedPersonId,new SelectList(Model.persons,"Id","Name","--Select--"))
</div>

【讨论】:

  • 非常感谢我对其进行了测试,但在行 Html.DropDownListFor(x=>x.SelectedPersonId,new SelectList(Model.persons,"Id","Name","--Select--" )) 给出了这个错误:ObjectContext 实例已被释放,不能再用于需要连接的操作。
  • 它和我一起工作......使用.ToList()尝试一下我会更新答案
  • 谢谢,但如果我删除使用它会产生该错误,为什么会发生该错误?使用 (KCMDBEntities KCMDB = new KCMDBEntities()) { }
  • 谢谢 3nigma 你帮了我很好你的样本很有帮助。非常感谢 3nigma
【解决方案2】:

如果您想使用 MVC HtmlHelpers 中的构建,您应该将其转换为 List&lt;SelectListItem&gt;

  @Html.DropDownFor(x => x.SelectedPerson, Model.PersonList)

或者,您可以简单地在模板中制作自己的:

<select id="select" name="select">
@foreach(var item in Model.PersonList)
{
   <option value="@item.id">@item.name</option>
}
</select>

【讨论】:

  • 我想使用@Html.DropDownListFor(...) 现在怎么办?
猜你喜欢
  • 2014-01-10
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2012-04-30
  • 2018-02-10
相关资源
最近更新 更多