Search code examples
validationasp.net-mvc-4drop-down-menumvc-editor-templates

EditorTemplate DropDown gets wrong id and cant get validated


I have made an EditorTemplate in MVC 4 with this code:

@model Drexx.Models.Account
@Html.DropDownListFor(model => model.LevelId, (IEnumerable<SelectListItem>)ViewBag.LevelId, String.Empty)

My View has this code:

@Html.EditorForModel();

My Model has this code:

[UIHint("LevelDropDown")]
[DisplayName("Level")]
public int LevelId { get; set; }
public virtual Level Level { get; set; }

My Controller has this code in the Get:

ViewBag.LevelId = new SelectList(db.Level, "Id", "Name");

My Controller has this code in the Post:

ViewBag.LevelId = new SelectList(db.Level, "Id", "Name", account.LevelId);

This is how the source code looks when i run it:

<select data-val="true" data-val-number="The field Level must be a number." data-val-required="Feltet Level skal udfyldes." id="LevelId_LevelId" name="LevelId.LevelId">
    <option value=""></option>
    <option value="1">Normal</option>
    <option value="2">Admin</option>
</select>
<span class="field-validation-valid" data-valmsg-for="LevelId" data-valmsg-replace="true"></span>

why is it making the id of the dropdown into "LevelId_LevelId" and the name into "LevelId.LevelId"? The dropdown works and shows what it should, but the validation dont work since the id/name is wrong. the validation highlights the dropdown, but it does not display the error message.

The dropdown worked perfectly fine before i moved it into EditorTemplate/before i started using EditorForModel

Im new to EditorTemplates so have a hard time figuring out what could cause this.


Solution

  • I found the solution.

    Model should look like this:

    [DisplayName("Level")]
    [UIHint("LevelId")]
    [Required]
    public int? LevelId { get; set; }
    

    The EditorTemplate should look like this:

    @model int?
    @Html.DropDownListFor(model => model, (IEnumerable<SelectListItem>)ViewBag.LevelId, String.Empty)
    

    It is very important that i put the "?" after the int because i have a default value in the dropdown.

    I didnt have to create a ViewModel for the dropdown.

    This is how the source ended up looking after the fix:

    <div class="editor-field">
        <select data-val="true" data-val-number="The field Level must be a number." data-val-required="Feltet Level skal udfyldes." id="LevelId" name="LevelId">
            <option value=""></option>
            <option value="1">Normal</option>
            <option value="2">Admin</option>
        </select>
        <span class="field-validation-valid" data-valmsg-for="LevelId" data-valmsg-replace="true"></span>
    </div>
    

    Thanks for all the suggestions Darin Dimitrov, but they didnt work for me.