从List <mytype>创建DropDownListFor

时间:2017-11-12 16:44:20

标签: asp.net asp.net-mvc asp.net-core

我有以下课程:

public class Nationality
{
    public int ID { get; set; }
    public string name { get; set; }
}

public class PersonalData
{
    public List<Nationality> availableNationalities { get; set; }

    public PersonalData()
    {
        availableNationalities = new List<Nationality>();
    }
}

在我看来,我想使用DropDownlistFor上的availableNationalities字段创建PersonalData

遵循一段视图代码和我正在尝试的示例:

@model PersonalData
@Html.DropDownListFor(
                    model => model.personalData.nationality,
                    new SelectList(Model.availableNationalities, "ID", "name"),
                    "Choose please an option",
                    new { required = "required" }
                )

提前谢谢

1 个答案:

答案 0 :(得分:1)

由于personalData视图模型上没有PersonalData属性,您的代码将抛出异常。

在视图模型中再添加一个属性以存储选定的选项值

public class PersonalData
{
    public int SelectedNationality { set;get;}
    public List<Nationality> AvailableNationalities { get; set; }

    public PersonalData()
    {
        AvailableNationalities = new List<Nationality>();
    }
}

现在在您的视图中,您可以使用select标记帮助程序(在ASP.NET Core应用程序中)

@model PersonalData
<form asp-controller="Home" asp-action="Create">

    <select asp-for="SelectedNationality" 
            asp-items="@(new SelectList(Model.AvailableNationalities ,"Id","Name"))">
        <option>Please select one</option>
    </select>
    <input type="submit"/>
</form>

如果是非核心应用,您可以使用DropDownListFor帮助

@Html.DropDownListFor(
                       a=> a.SelectedNationality,
                       new SelectList(Model.AvailableNationalities, "ID", "name"),
                       "Choose please an option",
                       new { required = "required" }
                    )

假设您的GET操作方法在AvailableNationalities viewmodel对象上设置PersonalData属性,然后再将其发送到视图。

public IActionResult Create()
{
   var vm=new PersonalData 
   {
     AvailableNationalities = new List<Nationality>
     {
         new Nationality { Id=1, Name="USA"},
         new Nationality { Id=2, Name="Canada"},
     }
   }; 
   return View(vm); 
}

如果你只关心在视图中渲染SELECT元素,你可以简单地使用List<SelectListItem>而不是List<Nationality>,如this post中所述