[英]Model binding fof List
I currently Use a ViewModel to show DropDown items, thanks to proprety I use to fill dropdown's (professionsSelect). 我现在使用ViewModel来显示DropDown项,这要归功于我用来填充dropdown的属性(professionsSelect)。 value are stored into a list (professions).
值存储在列表中(专业)。
Here is the sample of my DocumentViewModel: 这是我的DocumentViewModel的示例:
[Required]
public List<Profession> professions { get; set; }
public IEnumerable<SelectListItem> professionsSelect { get; set; }
Here's Profession Model sample: 这是行业模型示例:
public class Profession
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public bool isActive { get; set; }
}
Now, for instance, to insert data into DB, I use a Model, corresponding to the Model. 现在,例如,要将数据插入数据库,我使用一个与该模型相对应的模型。 I use a Mapper to transform VM to Model:
我使用Mapper将VM转换为Model:
Mapper.CreateMap<DocumentViewModel, BE.Document>();
IList<BE.Document> destination = Mapper.Map<IList<BE.Document>>(document);
But the problem is that When I receive VM on the controller, there is no data into destination list: 但是问题是当我在控制器上收到VM时,目标列表中没有数据:
[HttpPost]
public ActionResult Create(DocumentViewModel model)
{
if (ModelState.IsValid)
{...}
}
How Can the model bindong I fill the List IList of the ViewModel? 模型绑定如何填充ViewModel的列表IList?
Here is how I do to show data ot user on creation form: 这是我如何在创建表单上向用户显示数据:
<div class="form-group">
@Html.LabelFor(model => model.professions, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.ListBoxFor(model => model.professions, Model.professionsSelect, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.professions, "", new { @class = "text-danger" })
</div>
</div>
One possible solution should be to create a new property to viewModel int[] ProfessionIds but it is unclear, 3 properties for one fidls, that's definitiverly too mutch for me. 一种可能的解决方案应该是为viewModel int [] ProfessionIds创建一个新属性,但目前尚不清楚,对于一个fidl,有3个属性,这对我来说绝对太有用了。
Thanks to help me 谢谢帮我
You cannot bind a <select multiple>
to a collection of complex objects (in your case Profession
). 您不能将
<select multiple>
绑定到复杂对象的集合(在您的情况下为Profession
)。 It only posts back an array of value types (the values of the selected options). 它只回发一个值类型数组(所选选项的值)。
Your model needs a property (say) 您的模型需要一个属性(例如)
public int[] SelectedProfessions { get; set; } // or List<int>
assuming your wanting to post back a collection of the Profession.id
假设您要发回
Profession.id
的集合
Then the view will be 然后视图将是
@Html.ListBoxFor(m => m.SelectedProfessions, Model.professionsSelect, new { @class = "form-control" })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.