我想知道如何使用<SelectListItem>
ASP.NET MVC 中的类型正确实现下拉框。我以前没有使用过这种方法,并且我被告知如果我必须对下拉菜单执行“必需”验证,这是最好的方法。
我之前使用 ViewBag 创建了一个下拉菜单,但我认为这种方法不是很有效。
我这里的例子很简单。一个允许用户输入客户姓名并从下拉列表中选择国家的小应用程序。它还应该检查用户是否选择了一个国家并在名称文本框中输入了一个值。请在下面查看我的代码。它不完整,只是一个模板,所以请帮助我如何完全实现这种方法。如果使用它是有效的,也请随意使用存储库。我仍在努力理解如何使用存储库模式,因此也需要帮助和解释。谢谢
客户视图模型
public class Customer
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public Country CountryId { get; set; }
}
public class Country
{
public int CountryId { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
}
模型
- 客户- EntityFramework 实体包含一个客户详细信息表,其中包含国家实体的外键
- 国家- 包含 CountryId 和 CountryName 表的实体
行动结果
Models.EFEntities ctx = new Models.EFEntities();
public ActionResult GetCustomers()
{
using(ctx)
{
Need code to properly implement this part
}
return view("Customers");
}
[HttpPost]
public ActionResult AddCustomer(Model.Customer customer)
{
using(ctx)
{
//I'm thinking of calling the SaveChanges() method on Customers Entity,
//but please let me know if you have any better ways of writing this code.
// something like using repository pattern)
}
return view();
}
客户视图 该视图显示了一个简单的界面,用于输入客户名称并从 dorp-down 中选择一个国家。我认为它应该类似于下面的那个
@model Models.Customer
@Html.EditorFor(model=>model.Name)
@Html.ValidationFor(model=>model.Name)
@Html.DropDownListFor(model => model.Country..?..Need code here as well, "please select")
@Html.ValidationFor(...Need code here to make sure the user selects a country)