asp.net-mvcinputmvc-editor-templateseditortemplates

MVC Input name wrong


I want to use a (bootstrap) modal to show a translationdialog but it's giving a wrong name. In the browser sourcecode it shows NameTranslations.[0].Translation while it have to be NameTranslations[0].Translation (without the dot between NameTranslation and the [i]).

Some code :

Views/Shared/EditorTemplate/Translation.cshtml

@model List<Data.ViewModels.Shared.TranslationViewModel>

@for (var i = 0; i < Model.Count; i++)
{
    @Html.TextBoxFor(m => Model[i].Translation)
}

Create.cshtml

    @Html.EditorFor(model => Model.NameTranslations,"Translation")

BrowserResult

<input id="NameTranslations__0__Translation" name="NameTranslations.[0].Translation" type="text" value="">

Everything work greats except the name convention is wrong. If I delete the dot in the browsercode, it is well posted in the controller.


Solution

  • I fixed this with a ViewData

    Create.cshtml

    @model List<Data.ViewModels.Shared.TranslationViewModel>
    @{
        var ModelName = ViewData["ModelName"];
    }
    

    Partial View: Views/Shared/_Translation.cshtml

    @for (var i = 0; i < Model.Count; i++)
    {
        var LanguageID = ModelName + "[" + i + "].LanguageID";
        var TranslationName= ModelName + "[" + i + "].Translation";
    
        <input type="hidden" name="@LanguageID" value="@Model[i].LanguageID" />
        <input type="text" name="@TranslationName" value="@Model[i].Translation" />
        <br />
    }
    

    I think it isn't the best way to do it but if there's a change in a ViewModel, you can replace it in one place (partial) instead of several.