我有使用ModelMetadata
显示所有对象的属性的观点:下拉为对象列表中的自定义编辑器
@foreach (var property in ViewData.ModelMetadata.Properties)
{
<div class="form-group">
@Html.Label(property.PropertyName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Editor(property.PropertyName, new { htmlAttributes = new { @class = "form-control" }, Context = context })
@Html.ValidationMessage(property.PropertyName, "", new { @class = "text-danger" })
</div>
</div>
}
但我的模型有一个属性:
[Required]
public virtual User Owner { get; set; }
据推测显示用户列表的下拉列表,以便我可以选择一个。 我已经添加了以下编辑模板在Views\Shared\EditorTemplates\User.cshtml
:
@using Views.Projects
@model Models.Users.User
@{
Layout = null;
var context = (ProjectContext) ViewData["Context"];
var elements = new SelectList(context.AvailableUsers, Model);
}
@Html.DropDownListFor(x => x, elements)
,但似乎变化并不适用 - 我选择无论用户是不会保存在对象和验证失败(因为业主== null,而它是必需的)
如何使这项工作?
更新
原始的HTML生成:
<div class="form-group">
<label class="control-label col-md-2" for="Owner">Owner</label>
<div class="col-md-10">
<select id="Owner" name="Owner">
<option>User1</option>
<option>User2</option>
<option>User3</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="Owner" data-valmsg-replace="true"></span>
</div>
</div>
您可以请分享与所有者/用户属性相对应生成的字段的名称吗? – sachin
MVC已经有这个('EditorForModel()'或'EditorFor(m => m)') –
@sachin不知道我明白。我的'项目'有'用户拥有者{get; set}'。 'User'有一堆属性,比如'string Name,string Initials',但这里并不重要。 – Archeg