Question

I am making my first tentative steps into MVC3 and have come across an issue with the translation of navigation properties within a model to a view. It seems that in the view navigational properties do not allow client side validation nor is the "Display" label attribute picked up.

I have the following simple model:

public class Entity
{
    [Key,
    ScaffoldColumn(false)]
    public int Entity_Id { get; set; }

    [Display(Name = "Entity Name"),
    Required(ErrorMessage = "Please enter the entity name."),
    StringLength(150, ErrorMessage = "Please ensure that the entity name is under 150 characters.")]
    public string Entity_Nm { get; set; }

    [Display(Name = "Entity Type"), 
    Required(ErrorMessage="Please select the entity type"),
    ForeignKey("EntityType")]
    public int EntityType_Id { get; set; }

    public virtual EntityType EntityType { get; set; }
}

Which references this model:

public class EntityType
{
    [Key]
    public int EntityType_Id { get; set; }

    [Display(Name = "Entity Name"), Required(ErrorMessage="Please enter the entity type name.")]
    public string EntityType_Nm { get; set; }
}

When I create a controller with read/write actions and views for this model I get the following create form:

<fieldset>
    <legend>Entity</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Entity_Nm)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Entity_Nm)
        @Html.ValidationMessageFor(model => model.Entity_Nm)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.EntityType_Id, "EntityType")
    </div>
    <div class="editor-field">
        @Html.DropDownList("EntityType_Id", String.Empty)
        @Html.ValidationMessageFor(model => model.EntityType_Id)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

This is fine apart from the label for the Entity Type drop down, for some reason it is not picking up the "Display" attribute of the navigation property within the model (note the lack of a space). Also client side validation is not enabled for the dropdown list (server side validation works without issue) despite decorating the property with a "Required" attribute. Client side validation works on the other fields. Please note that all the required .js script files have been included and I have also added the relevant enable validation keys to the web.config.

Any ideas what I am missing here? Thanks one and all.

Was it helpful?

Solution

for DropDownList Display issue just try below

@Html.LabelFor(model => model.EntityType_Id)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top