asp.net-mvceditortemplates

MVC 5 EditorTemplate for Model renders with same id and name


I have Parent model "Receipt" and it has dictonary of objects as a property called CustomControlDictionary of class CustomControlModel. In my view i loop throuh each object in CustomControlDictionary property and call EditorTemplate. In the template i simply add label and textbox for my CustomControlModel object. When code renders html controls have same id and name attributes : id="key_Value" name="key.Value" . I did try using regualr arrays or lists instead of dictionary ,but with same result. Looking forward for any advise.

Model:

public class ReceiptModel 
{
    public ReceiptModel(){}
    public int ReceiptId { get; set; }
    public string ReceiptNumber { get; set; }
    public Dictionary<string, CustomControlModel> CustomControlDictionary{get; set; }
    // public List<CustomControlModel> CustomControlList { get; set; }
}


public class CustomControlModel 
{
    public CustomControlModel(){}
    public int CustomControlId{ get; set; }
    public string CustomControlName{ get; set; }
    public string LabelCaption{ get; set; }
    public string Value{ get; set; }
}   

View:

//View (@ReceiptModel):
@foreach (var key in Model.CustomControlDictionary )
{
    @Html.EditorFor(m => key.Value,"CustomControlModel")
}

Editor Template:

@model EWMS_MVC.Classes.CustomControlModel

@Html.HiddenFor(model => model.CustomControlId)
@Html.LabelFor(model => model.CustomControlId, Model.LabelCaption)
@Html.TextBoxFor(model => model.CustomControlId, new { @Value = @Model.Value })

Rendered html has same id and name for all obects in CustomControlDictionary property of ReceiptModel:

<input id="key_Value_CustomControlId" name="key.Value.CustomControlId" type="hidden" value="201922" />//value here should be "id" of the input field
<label for="key_Value_CustomControlId">Receipt number:</label>
<input id="key_Value_CustomControlId" name="key.Value.CustomControlId" type="text" value="201922" />//value here should be "id" of the input field

Solution

  • I think the best approach for this situation would be to avoid the HtmlHelper methods in your template and use html controls instead:

    @model EWMS_MVC.Classes.CustomControlModel
    <label>@Model.LabelCaption</label>
    <input id="@Model.CustomControlId" name="@Model.CustomControlName" type="text" value="@Model.Value" />