MVC模型绑定和DropDown列表

时间:2010-08-14 05:40:47

标签: asp.net-mvc drop-down-menu

我有一个显示在下面的Person类。在视图中,我需要显示其属性,以及存在于不同表中的DepartmentName。下面的类中的DepartmentId是外键。我正在使用Linq to SQL。我还在下面显示我的PersonRepository和Controller代码。我需要在“索引视图”页面中显示DepartmentName,在“编辑视图”页面上显示下拉列表。我是MVC的新手,所以我不知道该怎么做。非常感谢任何帮助。

public class Person_Validation
{
    [HiddenInput(DisplayValue = false)]
    [ScaffoldColumn(false)]
    public object PersonId { get; set; }

    [HiddenInput(DisplayValue = false)]
    [ScaffoldColumn(false)]
    public object DepartmentId { get; set; }

    [DisplayName("First Name")]
    [Required(ErrorMessage = "First Name is required")]
    [StringLength(50, ErrorMessage = "Frist Name cannot be more than 50 characters")]
    public object FirstName { get; set; }

    [DisplayName("Last Name")]
    [Required(ErrorMessage = "Last Name is required")]
    [StringLength(50, ErrorMessage = "Last Name cannot be more than 50 characters")]
    public object LastName { get; set; }

    [HiddenInput(DisplayValue = false)]        
    public object Active { get; set; }

    [HiddenInput(DisplayValue = false)]
    public object DateAdded { get; set; }

    [HiddenInput(DisplayValue = false)]
    public object DateDeleted { get; set; }

    public IEnumerable<Department> departments { get; set; }             
}

PersonRepository类

public IList<Person> GetAllPersons()
{
    //get all active people
    var activePeople = from p in db.Persons
                       where p.Active == true
                       select p;

    return activePeople.ToList();            
}

控制器代码:

public ActionResult Index(int? page)
{
    const int pageSize = 25;

    var persons = _repository.GetAllPersons();            
    var paginatedPersons = new PaginatedList<Person>(persons, page ?? 0, pageSize);

    return View(paginatedPersons);
}

2 个答案:

答案 0 :(得分:0)

我建议你从这里http://valueinjecter.codeplex.com查看asp.net mvc示例,特别是 TinyController ,我认为这是做mvc的最好方法

答案 1 :(得分:0)

我想分享这个链接,你可以通过各种方式使用MVC绑定下拉列表

http://www.c-sharpcorner.com/UploadFile/deveshomar/ways-to-bind-dropdown-list-in-Asp-Net-mvc/

它可能对您有所帮助。