0

我想知道如何使用<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; } 
}

模型

  1. 客户- EntityFramework 实体包含一个客户详细信息表,其中包含国家实体的外键
  2. 国家- 包含 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)
4

1 回答 1

1

将选择列表包含在您的Customer

public class Customer
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public int CountryId { get; set; }

    public IEnumerable<SelectListItem> Countries { get; set; } 
}

在您的控制器中构建模型,如下所示:

public ActionResult GetCustomers()
{
    var model = new Customer();
    using(ctx) 
    {
        // Need code to properly implement this part 
        // > I assume you know how to do this, something like:
        var customer = ctx.Customers.Get(the_id);
        // map the entity to your model
        model.Id = customer.Id;
        // map the rest of the fields here (you may want to use mapper tools)

        // get the country list from your db and map it to selectlistitem
        model.Countries = mapCountries(ctx.Countries.GetAll());
    }
    return view(model);
}

你的看法

@model Models.Customer

@Html.EditorFor(model=>model.Name)
@Html.ValidationFor(model=>model.Name)
// implement the rest of your fields
@Html.DropDownListFor(model => model.CountryId, Model.Countries, "please select")
@Html.ValidationFor(model => model.CountryId)

然后在你的 post 方法中

  1. 确保模型有效(服务器端验证)
  2. 将您的模型映射回您的实体
  3. 将实体保存到数据库

基本上就是这样,您只需要使用特定于您的项目的代码填写空白即可。

于 2013-04-09T10:03:05.443 回答