2016-09-16 58 views
0

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

您可以請分享與所有者/用戶屬性相對應生成的字段的名稱嗎? – sachin

+1

MVC已經有這個('EditorForModel()'或'EditorFor(m => m)') –

+0

@sachin不知道我明白。我的'項目'有'用戶擁有者{get; set}'。 'User'有一堆屬性,比如'string Name,string Initials',但這裏並不重要。 – Archeg

回答

1

你將不得不使用在EditorTemplateUser產生的下拉:

@Html.DropDownListFor(x => x.Name, elements) 

@Html.DropDownListFor(x => x.ID, elements) 

Select字段的名稱必須指向User(ID或名稱無論如何)的唯一屬性之一。如果字段名稱只是User而不是User.IDUser.Name,則模型聯編程序不知道要綁定的用戶屬性。

+0

如果我這樣做,那將改變用戶名稱,但我想更改項目中的整個用戶。或者我想念一些重要的概念?我剛剛開始使用MVC – Archeg

+0

然後將下拉列表綁定到用戶的ID。提交的用戶/所有者對象只有ID,它應該用於通過外鍵或其他方式將用戶/所有者與模型鏈接起來。 – sachin

+0

這可以工作,但這是非常不愉快的方式。它會破壞我的模型,並會使用所有這些編輯器添加很多我想避免的代碼。 MVC無法獨自完成這些事情是很奇怪的。我只想選擇一個對象作爲另一個對象的編輯器 – Archeg

相關問題