【问题标题】:MVC : how to select specific column/field from model object for drop downMVC:如何从模型对象中选择特定的列/字段进行下拉
【发布时间】:2013-07-01 11:30:21
【问题描述】:

我在视图中有以下模型和简单的下拉菜单。我想在下拉列表中填充客户名称。我尝试了以下代码,但没有成功,谁能告诉我如何使用 dropdownselect 语句指定列。

型号

public class customer
{

    public int id { get; set; }
    public string name { get; set; }
    public string address { get; set; }

}

///////////////////////

  @{
Layout = null;
}

@model IEnumerable<MvcApplication1.customer>

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>

    @Html.DropDownList("name",Model);

</div>

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 razor


    【解决方案1】:

    你可以使用this overload:

    @Html.DropDownList("name",new SelectList(Model,"id","name"));
    

    更新:

    您的模型没有名称属性。它只包含具有 name 属性的对象。您应该更新您的模型以反映这一点:

    class MyViewModel
    {
        public IEnumerable<customer> CustomerList { get; set; }
        public string SelectedCustomer { get; set; }
    }
    

    然后将您的视图强输入到这种类型:

    @model MyViewModel
    

    然后你就可以创建下拉菜单了:

    @Html.DropDownListFor(m => m.SelectedCustomer , new SelectList(Model.CustomerList ,"id","name"));
    

    【讨论】:

    • 如何使用 DropDownListFor?我尝试了以下但没有工作:( @Html.DropDownListFor(m=>m.name, new SelectList(Model,"id","name"));
    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2013-09-09
    • 1970-01-01
    相关资源
    最近更新 更多