[英]DropDownListFor binding to model
I am new to asp.net mvc and despite several searches can't get my head successfully around drop down lists in a view. 我是asp.net mvc的新手,尽管进行了几次搜索都无法成功找到视图中的下拉列表。
Specifically I'm creating a project that is entity framework code first. 具体来说,我首先创建的项目是实体框架代码。
I have a form that requires the user to optionally pick the Licence Type they have. 我有一张表格,要求用户选择他们拥有的许可证类型。
And help or assistance would be greatly appreciated. 并且帮助或协助将不胜感激。 I'm looking to create a DropDownListFor helper in the view to enable the drop down list for LicenceType. 我正在寻找在视图中创建一个DropDownListFor助手,以启用LicenceType的下拉列表。
The GRCMember model section relating to licence type is: 与许可证类型有关的GRCMember模型部分是:
public class GRCMember
{
[Column(TypeName = "int")]
public int? LicenceTypeId { get; set; }
}
The Licence Type Model is: 许可证类型模型为:
public class LicenceType
{
public int LicenceTypeId { get; set; }
[StringLength(150)]
[Column(TypeName = "nvarchar")]
public String Type { get; set; }
[Column(TypeName = "bit")]
public bool? Dormant { get; set; }
public virtual ICollection<GRCMember> GRCMembers { get; set; }
}
The associated Register View Model section is: 相关的寄存器视图模型部分为:
public class RegisterViewModel
{
[Display(Name = "Licence Type")]
public int? SelectedLicenceTypeId { get; set; }
}
The get controller method is: get控制器方法是:
[AllowAnonymous]
[HttpGet]
public ActionResult Register()
{
return View();
}
And finally the drop down section of the view is: 最后,视图的下拉部分是:
@model GRCWebApp.Models.RegisterViewModel
<div class="col-md-3 col-md-offset-1">
@Html.LabelFor(model => model.SelectedLicenceTypeId, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.SelectedLicenceTypeId, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.SelectedLicenceTypeId, "", new { @class = "text-danger" })
</div>
Let's assume that you have two entities called Person and City. 假设您有两个名为Person和City的实体。 Then you would use a ViewModel in order to populate these two entities in a model as shown below: 然后,您将使用ViewModel来在模型中填充这两个实体,如下所示:
PersonViewModel: PersonViewModel:
public Person Person { get; set; }
public IEnumerable<City> Cities { get; set; }
The controller of course returns the ViewModel: 控制器当然会返回ViewModel:
Controller: 控制器:
public ViewResult Create()
{
PersonViewModel model = new PersonViewModel
{
Person = new Person (),
Cities = repository.Cities.ToList()
};
return View(model);
}
You should pass the ViewModel to your View and then use the Dropdownlist as shown below: 您应该将ViewModel传递给View,然后使用Dropdownlist,如下所示:
View: 视图:
@model Project.WebUI.Models.PersonViewModel
...
@Html.LabelFor(m => m.Person.City)
@Html.DropDownListFor(m => m.Person.City, new SelectList(Model.Cities, "CityID", "CityName"), "---- Select ----")
Hope this helps... 希望这可以帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.