MVC Input name wrong

672 views Asked by At

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.

3

There are 3 answers

0
PJDW On BEST ANSWER

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.

2
Oasis On

Assign the name attribute by specifying explicit value using new { name = yourdynamicName }

2
Zabavsky On

Make the changes to the Translation template to be an editor template for a single entity only:

@model Data.ViewModels.Shared.TranslationViewModel

@Html.TextBoxFor(m => m.Translation)
...

and iterate through the collection in the main view instead:

@for (int i = 0; i < Model.NameTranslations.Count; i++)
{
    @Html.EditorFor(m => m.NameTranslations[i], "Translation")
}