Search code examples
asp.net-mvcasp.net-mvc-5mvc-editor-templates

Remove MVC 5 EditorTemplate additional ID


I am using this Editor Template for Dropdownlist with ViewBag/ViewData of same property Name

@model System.String
@*
    For Using this Editor Template
    - There should be a viewbag/viewdata (type SelectList) of same name as of calling Model's Property
*@
@{
    var modelMetadata = ViewData.ModelMetadata;
    // Get property name of the model
    var propertyname = modelMetadata.PropertyName;
}

@if (ViewData[propertyname] == null)
{
    @Html.DropDownList(propertyname , Enumerable.Empty<SelectListItem>(), "--Select--", new { @class = "form-control" })
}
else
{
    @Html.DropDownList(propertyname , null, "--Select--", new { @class = "form-control" })
}

now using it as @Html.EditorFor(i=>i.Country,"CustomDropDown") I also have a ViewBag.Country as SelectList of countries.

Everything works fine, but now the Naming of the Control becomes

<select class="form-control" id="Country_Country" name="Country.Country">

how to remove the additional Country from the id and name?

Additional Info:

I could have just used the @Html.DropDownList("Country") but it doesn't allow me to add the css class to the control.


Solution

  • I think i found the Solution.

    I changed the DropDownList to DropDownListFor with some changes

    @if (ViewData[propertyname] == null)
    {
        @Html.DropDownListFor(m=>m, Enumerable.Empty<SelectListItem>(), "--Select--", new { @class = "form-control" })
    }
    else
    {
        @Html.DropDownListFor(m => m, ViewData[propertyname] as SelectList, "--Select--", new { @class = "form-control" })
    }
    

    this auto ViewData bind is kind of confusing at times. >_<