如何从mvc3中的数据库中获取dropdownlist中的数据。

时间:2011-06-10 15:01:56

标签: asp.net-mvc

我正在asp.net中使用MVC3设计一个简单的网页。我使用Sql Server准备了一个数据库,并在App_Data中附加了这个数据库。该数据库中有一名表员工。

我想在下拉列表中获取员工姓名。所以我可以选择员工的名字。

所以请在下拉列表中建议我访问员工姓名的型号,视图和控制器代码。

2 个答案:

答案 0 :(得分:2)

我首先要设计一个可以保存数据的视图模型:

public class EmployeeViewModel
{
    public string SelectedEmployeeName { get; set; }
    public IEnumerable<SelectListItem> Employees { get; set; }
}

然后是控制器:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        IEnumerable<Employee> employees = GetEmployeesFromDb();
        var model = new EmployeeViewModel
        {
            Employees = employees.Select(x => new SelectListItem
            {
                Value = x.Name,
                Text = x.Name
            })
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(EmployeeViewModel model)
    {
        return Content("Selected employee name: " + model.SelectedEmployeeName, "text/plain");
    }
}

最后是强类型视图:

@model EmployeeViewModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(
        x => x.SelectedEmployeeName,
        new SelectList(Model.Employees, "Value", "Text")
    )
    <input type="submit" value="OK" />
}

答案 1 :(得分:0)

1)创建一个方法来填充DB中的列表

2)设置ViewModel以保存List和选定的值

// MODEL

 public List<SelectListItem> CategoriesSelectList()
            {

                var query = from c in _yourRepository.GetAll()
                            select c;

                List<SelectListItem> obj = new List<SelectListItem>();

                foreach (var item in query)
                {

                    var result = new SelectListItem();
                    result.Text = item.name;
                    result.Value = item.id.ToString();
                    obj.Add(result);

                }
                return obj;
            }

//视图模型

public class ViewModel
{
 [DisplayName("Category")]
        public int categoryId { get; set; }
        public List<SelectListItem> CategoryList()
        {
            return new Model().CategoriesSelectList();
        }
}

// CONTROLLER

public ActionResult Create()
        {
            //set the id for the VIEWMODEL property, if necesary
            var e = new ViewModel();
            e.categoryId = 1;//set the selected value

            return View(e);
        }

// VIEW

<div class="editor-label">
    <%: Html.LabelFor(model => model.categoryId) %>
</div>
<div class="editor-field">
    <%: Html.DropDownListFor(model => model.categoryId,Model.CategoryList()) %>
    <%: Html.ValidationMessageFor(model => model.categoryId) %>
</div>