0

我正在尝试将 Dropdownlistfor 添加到我的 MVC 项目中,但没有成功。我想显示客户列表。我希望显示客户并选择 ID。

我正在努力将我的列表投射到 selectListItems 中,有人可以帮我解决这个问题。

控制器

public ActionResult createNewUser()
{

    List<string> Customers = DBH.CustomerBranchGetAll();

    var Model = new UserModel
    {
       Customers = Customers
    };

    return View(Model);

}

模型

public class UserModel
{

   public int CustomerId { get; set; }
   public List<string> Customers { get; set; }
   public IEnumerable<SelectListItem> SelectCustomers
   {
      get { return new SelectList(Customers, "Id", "Name"); }
   }
}

看法

<div class="editor-label">
    @Html.Label("Choose Your Customer name")
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.CustomerId, Model.SelectCustomers)
    @Html.ValidationMessageFor(model => model.Customers)
</div>
4

2 回答 2

2

读取选择列表

Customers不是包含Id & Name属性的对象。在您的代码中,它只是一个字符串列表。List<string> Customers

您需要定义一个具有 Name 和 Id 属性的类并使用它

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

然后准备一个分配了 Id 和 Name 属性的客户对象

List<Customers> customers = DBH.CustomerBranchGetAll(); 
var Model = new UserModel
{
   Customers = customers
};

在视图中

  @Html.DropDownListFor(model => model.CustomerId, 
                        new SelectList(Model.Customers,"Id","Name"))
于 2014-06-04T10:26:41.437 回答
1

SelectList有一个带有IEnumerable.. 的构造函数,所以你只需要这样做:

@Html.DropDownListFor(model => model.CustomerId, new SelectList(Model.Customers))

您可以完全删除该SelectCustomers属性。

于 2014-06-04T10:27:35.710 回答