MVC AutoComplete EditorFor使用Html.BeginCollectionItem时

DaG*_*eNL 5 html javascript asp.net-mvc jquery razor

我正在尝试创建一个自动完成文本框,同时使用EditorTemplate.我面临的问题是,通过使用Html.BeginCollectionItem()扩展解决方案(https://www.nuget.org/packages/BeginCollectionItem/),动态设置EditorFor()TextBoxFor()方法的Id ,这会破坏我的javascript.接下来,我不知道这是否可能(如果是这样,如何.下面你会发现我到底有多远).

在主视图中,我有一个循环来为集合中的每个项生成局部视图

for (int i = 0; i < Model.VoedingCollection.Count; i++)
{
    @Html.EditorFor(x => x.VoedingCollection[i], "CreateVoedingTemplate")
}
Run Code Online (Sandbox Code Playgroud)

局部视图CreateVoedingTemplate.cshtml使用该Html.BeginCollectionItem()方法

@using (Html.BeginCollectionItem("VoedingCollection"))
{
    string uniqueId = ViewData.TemplateInfo.HtmlFieldPrefix.Replace('[', '_').Replace(']', '_').ToString();
    string searchId = "Search_";
    string standaardVoedingId = "StandaardVoeding_";
    foreach (KeyValuePair<string, object> item in ViewData)
    {
        if (item.Key == "Count")
        {
            searchId = searchId + item.Value.ToString();
            standaardVoedingId = standaardVoedingId + item.Value.ToString();
        }
    }

    <div class="form-horizontal">   
       <div class="form-group" id=@standaardVoedingId>
            @Html.LabelFor(model => model.fk_standaardVoedingId, "Voeding naam", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.HiddenFor(model => model.fk_standaardVoedingId)
                    <input type="text" id='@searchId' placeholder="Search for a product"/>
                </div>
       </div>
    </div>

    <script type="text/javascript">
        var id = '@uniqueId' + '_fk_standaardVoedingId'.toString();
        var search = '@searchId'.toString();

        var url = '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "AgendaApi" })';

        $(document.getElementById(search)).autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: url,
                    data: { query: request.term },
                    dataType: 'json',
                    type: 'GET',
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.standaardVoedingNaam,
                                value: item.standaardVoedingId
                            }
                        }));
                    }
                })
            },
            select: function (event, ui) {
                $(document.getElementById(search)).val(ui.item.label);
                //$('#id').val(ui.item.value);
                document.getElementById(id).value = ui.item.value;
                return false;
            },
            minLength: 1
        });
    </script>
}

<link href="~/Content/SearchBox/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/SearchBox/jquery-1.9.1.js"></script>
<script src="~/Scripts/SearchBox/jquery-ui.js"></script>
Run Code Online (Sandbox Code Playgroud)

在上面的脚本中,我试图创建一个函数,用户可以在其中键入standaardVoeding项的名称,然后获取结果,在用户选择standaardVoeding项后,standaardVoedingId属性设置.然后,在提交整个表单后,控制器会收到standaardVoedingId(包含所有其他信息)

所以我猜Javascript以某种方式无法处理Razor View @代码,并且旁边有Html.BeginCollectionItem一些可疑的东西,因为你无法在运行时通过代码设置其文本框的值.接下来,我尝试过alert(document.getElementById(*html.begincollectionitemId*)),它发现字段很好.但显然所有其他方法都不起作用?

是否有更好的解决方案让这个工作?

小智 1

BeginCollectionItem()方法会更改内置助手生成的 html 的idname属性,在您的情况下,用于隐藏输入,而不是

<input ... name="fk_standaardVoedingId" .... />
Run Code Online (Sandbox Code Playgroud)

它会生成

<input ... name="VoedingCollection[xxxx].fk_standaardVoedingId" .... />
Run Code Online (Sandbox Code Playgroud)

哪里xxxx是 a Guid.

虽然可以使用 javascriptGuid从文本框中提取值(假设使用 ind 正确生成@Html.TextBoxFor())并构建关联的隐藏输入的 id 以用作选择器,但使用类名和相对选择器要容易得多。

您还需要从部分中删除脚本和 css 并将其放入主视图(或其布局)中。除了内联脚本之外,您还可以为集合中的每个项目复制它。

你的部分需要是

@using (Html.BeginCollectionItem("VoedingCollection"))
{
    <div class="form-horizontal">   
       <div class="form-group">
            @Html.LabelFor(model => model.fk_standaardVoedingId, "Voeding naam", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10 item"> // add class name
                @Html.HiddenFor(model => model.fk_standaardVoedingId)
                <input type="text" class="search" placeholder="Search for a product"/>
            </div>
       </div>
    </div>
}
Run Code Online (Sandbox Code Playgroud)

请注意文本框及其容器的类名称,其中还包括隐藏的输入。然后在主视图中,脚本将是

<script type="text/javascript">
    var url = '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "AgendaApi" })';
    // Attach the script to all textboxes
    $('.search').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: url,
                data: { query: request.term },
                dataType: 'json',
                type: 'GET',
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.standaardVoedingNaam,
                            value: item.standaardVoedingNaam, // this needs to be the name
                            id: item.standaardVoedingId // add property for the id
                        }
                    }));
                }
            })
        },
        select: function (event, ui) {
            // Get the associated hidden input
            var input = $(this).closest('.item').find('input[type="hidden"]');
            // Set the value of the id property
            input.val(ui.item.id);
        },
        minLength: 1
    });
</script>
Run Code Online (Sandbox Code Playgroud)

根据您的评论,您没有在视图中动态添加或删除项目,那么额外的开销或使用该BeginCollectionItem()方法是没有意义的。将部分的名称更改为standaardvoeding.cshtml(假设这是类的名称)并将其移动到/Views/Shared/EditorTemplates文件夹中。

然后在主视图中,将for循环替换为

@Html.EditorFor(m => m.VoedingCollection)
Run Code Online (Sandbox Code Playgroud)

这将为集合中的每个项目生成正确的 html。最后从模板中删除该BeginCollectionItem()方法,以便它只是

<div class="form-horizontal">   
   <div class="form-group">
        @Html.LabelFor(m => m.fk_standaardVoedingId, "Voeding naam", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10 item"> // add class name
            @Html.HiddenFor(m => m.fk_standaardVoedingId)
            <input type="text" class="search" placeholder="Search for a product"/>
        </div>
   </div>
</div>
Run Code Online (Sandbox Code Playgroud)