Search code examples
asp.net-mvcdata-annotationsmvc-editor-templates

MVC 5 : NameForModel render twice the name and id of a field


I try to modify an editor template to use the data annotations. And I get some weird thing. Here below the editorTemplate.

@model Translations<string>

@{

    Translation<string> t = null;
    if (Model != null && Model.Values != null)
    {
        t = Model.Values.FirstOrDefault(p => p.Language == KalowContext.Instance.CurrentLanguage);
    }
    t = t ?? new Translation<string>();

    var validationAttributes = Html.GetUnobtrusiveValidationAttributes("");
}

@Html.TextBox(Html.NameForModel().ToString(), t.Value, new RouteValueDictionary(validationAttributes)
    {
        { "class", "form-control" }
    }
    )


<input class="form-control" type="text" name="@(Html.NameFor(m => Model))" value="@t.Value">

and this is the output, as you can the @Html.TextBox is rendering the name and the id attributes twice. Which works fine in the second input.

    <input name="dc.Name.dc.Name" class="form-control" id="dc_Name_dc_Name" type="text" value="Afghanistan" data-val-required="The Name field is required." data-val="true">
    <input name="dc.Name" class="form-control" type="text" value="Afghanistan">

Any suggestions ? Thank you !

Here is the class Translations and Translation

public class Translations<T>
{
    public List<Translation<T>> Values { get; set; }

    public Translations()
    {

    }
}


public class Translation<T>
{
    public ObjectId Language { get; set; }

    public T Value { get; set; }

    public Translation()
    {

    }

    public Translation(ObjectId language, T value)
    {
        Language = language;
        Value = value;
    }

}

Solution

  • <input class="form-control" type="text" name="@(Html.NameFor(m => Model))"
       @Html.Raw(string.Join(" ", 
           validationAttributes.
              Select(x => x.Key.ToString() + "=\"" + x.Value + "\"")))
                  value="@t.Value">
    

    Intermediate solution... but as there is no audience. I keep it that way. :=)