【发布时间】:2011-11-19 10:36:48
【问题描述】:
我正在使用 asp.net 中的 MVC3 设计一个简单的网页。我使用 Sql Server 准备了一个数据库,并将该数据库附加到 App_Data 中。该数据库中有一个员工表。
我想在下拉列表中获取员工姓名。所以我可以选择员工的姓名。
所以请建议我在下拉列表中访问员工姓名的模型、视图和控制器代码。
【问题讨论】:
标签: asp.net-mvc
我正在使用 asp.net 中的 MVC3 设计一个简单的网页。我使用 Sql Server 准备了一个数据库,并将该数据库附加到 App_Data 中。该数据库中有一个员工表。
我想在下拉列表中获取员工姓名。所以我可以选择员工的姓名。
所以请建议我在下拉列表中访问员工姓名的模型、视图和控制器代码。
【问题讨论】:
标签: asp.net-mvc
我将从设计一个保存数据的视图模型开始:
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" />
}
【讨论】:
GetEmployeesFromDb 方法是您应该编写的方法,它将查询数据库并返回Employee 模型。你不需要另一个控制器。您可以定义一个存储库类并将您的数据访问逻辑放在这个存储库类中。所以GetEmployeesFromDb 会进入存储库。
1) 创建一个方法来从数据库中填充列表
2) 设置一个 ViewModel 来保存列表和选定的值
//型号
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();
}
}
//控制器
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);
}
//查看
<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>
【讨论】: