我有使用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