Archeg Archeg - 6 months ago 37
C# Question

Dropdown as a custom editor for object list

I have a view that displays all the object's properties by using


@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" })

But my Model has the next property:

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

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


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">
<span class="field-validation-valid text-danger" data-valmsg-for="Owner" data-valmsg-replace="true"></span>


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

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


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