简体   繁体   English

当用户单击文本输入框时如何在@Html.EditorFor() 中显示下拉列表

[英]How to show dropdown list in the @Html.EditorFor() when user clicks on the text input box

I am passing data from the Controller to the View using the ViewData我正在使用 ViewData 将数据从控制器传递到视图
Code in the controller:控制器中的代码:

public ActionResult Create()
        {
            ViewData["gN"] = new SelectList(db.gT, "id", "gN");
            return View();
        }

In the View I am using @Html.EditorFor() to create the new item for our table which we store in the database.在视图中,我使用 @Html.EditorFor() 为我们存储在数据库中的表创建新项目。

<div class="col-md-10">
     @Html.EditorFor(model => model.gT.gN, new { htmlAttributes = new { @class = "form-control" } })
     @Html.ValidationMessageFor(model => model.groupid, "", new { @class = "text-danger" })
</div>

When I am using @Html.DropDownList our list of gN is perfectly showing as the dropdown list当我使用@Html.DropDownList 时,我们的 gN 列表完美地显示为下拉列表

 @Html.DropDownList("gN", null, htmlAttributes: new { @class = "form-control" })

I want to use EditorFor() so that when the user starts typing in the input box, the dropdown list appears below it.我想使用 EditorFor() 以便当用户开始在输入框中输入时,下拉列表会出现在它的下方。 and if that text which user is typing, present in the dropdown then the user can select it.如果用户正在键入的文本出现在下拉列表中,则用户可以选择它。 How we should show the list gN (which we are getting using ViewData from Controller) in the EditorFor() HTML element?我们应该如何在 EditorFor() HTML 元素中显示列表 gN(我们使用 Controller 中的 ViewData 获取)?

The Html.EditorFor() method always creates an <input> element, though the type attribute can vary depending on the model property type. Html.EditorFor()方法始终创建一个<input>元素,尽管type属性可能因模型属性类型而异。 HTML5 actually supports exactly what you want with the <datalist> element, which you tie to an <input> element with the list attribute. HTML5 实际上通过<datalist>元素完全支持您想要的内容,您可以将其绑定到具有list属性的<input>元素。 the <datalist> element takes child <option> elements containing the values you want in the list. <datalist>元素采用包含列表中所需值的子<option>元素。

Making some guesses about your models here...在这里对您的模型进行一些猜测...

// Controller
public ActionResult Create()
{
    ViewData["gN"] = db.gT;
    return View();
}

// View
@Html.EditorFor(model => model.gT.gN, new { htmlAttributes = new { @class = "form-control", list="gN-datalist" } })
<datalist id="gn-datalist">
    @foreach (var item in (gT)ViewData["gN"])
    {
        <option value="@item.id">@item.gN</option>
    }
</datalist>

You could also create an HtmlHelper extension method that would create this for you.您还可以创建一个HtmlHelper扩展方法来为您创建此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM