[英]Can I create drop down list while using editor for?
How do I create drop down list using data annotation? 如何使用数据注释创建下拉列表?
I would like to achieve markup generated by 我想实现由生成的标记
@Html.DropDownListFor(x=>x.ContactType, Model.ContactTypeOptions)
to be set so I can use and it would generate dropdown list: 进行设置,以便我可以使用,它将生成下拉列表:
@Html.EditorForModel(Model)
My current model is: 我当前的模型是:
public class ContactModel
{
public string ContactType { get; set; }
public IList<SelectListItem> ContactTypeOptions
{
get
{
return new List<SelectListItem>()
{
new SelectListItem(){Text = "Options"}
};
}
}
[Required(AllowEmptyStrings = false)]
[MinLength(15)]
[DataType(DataType.MultilineText)]
public string Message { get; set; }
}
Updated I do not want to use partial view. 更新后,我不想使用局部视图。
You could try something like this: 您可以尝试这样的事情:
public class ContactModel
{
[UIHint("_DropDownList")]
public SelectList ContactType { get; set; }
}
Set (in your controller) ContactType.Items
to be your list of options and ContactType.SelectedValue
to be your initially selected value. (在控制器中)将ContactType.Items
设置为选项列表,将ContactType.SelectedValue
设置为初始选择值。
Then define a partial view _DropDownList.cshtml : 然后定义局部视图_DropDownList.cshtml :
@model SelectList
@Html.DropDownListFor(m => m.SelectedValue, Model)
You should then be able to use @Html.EditorFor(m => m.ContactType)
and get your dropdown. 然后,您应该可以使用@Html.EditorFor(m => m.ContactType)
并获得下拉菜单。 And you can reuse it anywhere! 您可以在任何地方重用它!
You might even get this behaviour out of the box nowadays when you do @Html.EditorFor(m => m.Property)
where m.Property
is a SelectList
. 现在,当您执行@Html.EditorFor(m => m.Property)
, m.Property
当您使用m.Property
是SelectList
时,您甚至可能会发现这种行为。 Not sure on that one. 不确定那一个。
If you're looking to just use EditorForModel()
on your ContactModel
, then you can just create an editor template called ContactModel.cshtml
and do: 如果您只想在ContactModel
上使用EditorForModel()
,则可以创建一个名为ContactModel.cshtml
的编辑器模板,然后执行以下操作:
@model ContactModel
@Html.DropDownListFor(m => m.ContactType,
new SelectList(Model.ContactTypeOptions, Model.ContactType))
Note that this should be called as @Html.EditorForModel()
in a view already typed to a ContactModel
- the object passed in as a parameter in the overload EditorForModel(Object)
is for additional view data, not for the model object. 请注意,在已经键入到ContactModel
的视图中,这应该称为@Html.EditorForModel()
-作为重载参数传递给过载EditorForModel(Object)
用于其他视图数据, 而不用于模型对象。 EditorForModel
always renders an editor template for the current view model. EditorForModel
始终为当前视图模型呈现一个编辑器模板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.