Archeg
Archeg

Reputation: 8462

Dropdown as a custom editor for object list

I have a view that displays all the object's properties by using 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>
    }

But my Model has the next property:

[Required]
public virtual User Owner { get; set; }

It is supposed to show a dropdown with the list of users so I could select one. I have added the following editor template at 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)

But the changes doesn't seem to apply - whatever user I select is not saved in the object and validation fails (because the Owner == null, and it is required)

How do I make this work?

Update

Raw html generated:

<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>

Upvotes: 0

Views: 138

Answers (1)

sachin
sachin

Reputation: 2361

You'll have to use this for generating your DropDown in the EditorTemplate for User:

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

or

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

The name of Select field has to point to one of the Unique properties of User(ID or Name whatever is the case). The model binder doesn't know which property of user to bind to if the Name of field is just User and not User.ID or User.Name.

Upvotes: 1

Related Questions