I am trying to create an AutoComplete textbox, while using an EditorTemplate. The problem I am facing is that by using the Html.BeginCollectionItem()
The BeginCollectionItem() method alters the id and name attributes of the html generated by the inbuilt helpers, in your case, for the hidden input, instead of
it will generate
where xxxx is a Guid.
While it would be possible to use javascript to extract the Guid value from the textbox (assuming that was generated correctly usind @Html.TextBoxFor()) and build the id of the associated hidden input to use as a selector, it is far easier to use class names and relative selectors.
You also need to remove your scripts and css from the partial and put that in the main view (or its layout). Apart from the inline scripts, your duplicating it for each item in your collection.
Your partial needs to be
@using (Html.BeginCollectionItem("VoedingCollection"))
{
@Html.LabelFor(model => model.fk_standaardVoedingId, "Voeding naam", htmlAttributes: new { @class = "control-label col-md-2" })
// add class name
@Html.HiddenFor(model => model.fk_standaardVoedingId)
}
Note the class name for the textbox and its container which also includes the hidden input. Then in the main view, the script will be
Based on your comments that your are not dynamically adding or removing items in the view, then there is no point in the extra overhead or using the BeginCollectionItem() method. Change the name of your partial to standaardvoeding.cshtml (assuming that's the name of the class) and move it to the /Views/Shared/EditorTemplates folder.
Then in the main view, replace your for loop with
@Html.EditorFor(m => m.VoedingCollection)
which will generate the correct html for each item in the collection. Finally remove the BeginCollectionItem() method from the template so that its just
@Html.LabelFor(m => m.fk_standaardVoedingId, "Voeding naam", htmlAttributes: new { @class = "control-label col-md-2" })
// add class name
@Html.HiddenFor(m => m.fk_standaardVoedingId)