在两个文本框中分别自动完成返回值

时间:2019-05-19 08:36:56

标签: c# asp.net-mvc autocomplete

如何使自动完成表单在两个不同的文本框中返回值?例如,当使用自动完成表单选择苹果时,它将在文本框A中显示“ Apple”,在文本框B中显示数量“ 1”。

我尝试了以下代码,并成功构建了自动完成表单。但是它在选择中显示name,并且从列表中选择该项目时,它将显示value

<script type="text/javascript">
    $(document).ready(function () {
        $("#CardName").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/CardHolderDetails/Index",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.CardName, value: item.CardId };
                        }))

                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>
        <div class="form-group">
            @Html.EditorFor(model => model.CardName, new { htmlAttributes = new { @class = "form-control", id = "CardName" } })
        </div>  


        <div class="form-group">
            @Html.EditorFor(model => model.CardId, new { htmlAttributes = new { @class = "form-control", id = "CardId" } })
        </div>  
 [HttpPost]
        public JsonResult Index(string Prefix)
        {
            List<CardHolderDetails> getCardList = new List<CardHolderDetails>();
            getCardList = _service.getCardList();
            List<CardHolderDetails> ObjList = new List<CardHolderDetails>();
            foreach (var value in getCardList)
            {
                ObjList.Add(new CardHolderDetails { CardId = value.CardId, CardName = value.CardName });

            }

            //Searching records from list using LINQ query
            var CardName= (from N in ObjList
                            where N.CardName.StartsWith(Prefix)
                            select new { N.CardName, N.CardId });
            return Json(CardName, JsonRequestBehavior.AllowGet);
        }

我希望从自动完成表单中选择输出时,输出CardName将在文本框A中,而CardId将在文本框B中。

1 个答案:

答案 0 :(得分:0)

我试图了解问题的确切原因,但尚不清楚-是您还是没有使自动完成功能起作用?它是否将任何有意义的值返回给客户? 无论如何,我们在这里拥有的东西似乎似乎与Razor用法有关,可能与您使用返回对象的方式有关:

<div class="form-group">
        @Html.EditorFor(model => model.CardName, new { htmlAttributes = new { @class = "form-control", id = "CardName" } })
    </div>  


    <div class="form-group">
        @Html.EditorFor(model => model.CardId, new { htmlAttributes = new { @class = "form-control", id = "CardId" } })
    </div>  

从您要返回到客户端和Ajax脚本的模型中,我希望结果“模型”对象的用法如下所示: model => model.labelmodel => model.value