ASP.NET核心模型绑定:使用下拉列表作为标签

时间:2018-02-27 17:12:12

标签: c# html razor asp.net-core-mvc

我正在制作一个ASP.NET Core Mvc Web应用程序,正在处理搜索表单。在表单中,可以通过名字,姓氏,邮政编码以及ID,电子邮件或电话查找用户。用户是否输入ID,电子邮件或电话由下拉列表确定。我想将它绑定到我的用户模型,但不知道如何使用下拉列表动态地执行此操作。我能够绑定名字,姓氏和拉链,因为它们不是动态字段。我目前为表单提供的代码如下:

<form asp-action="Search">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group">
        <label for="sel1">Search By:</label>
            @* The dropdown menu to choose input type *@
            <select class="form-control" id="sel1">
                <option>ID</option>
                <option>Email</option>
                <option>Phone</option>
            </select>
     </div>
     @* Where users would input information for the dropdown field *@
     <div class="form-group">
         <label for="id">Value:</label>
         <input type="text" class="form-control clearable" id="id" Placeholder="0123456789">
    </div>
    <div class="form-group">
        <label asp-for="FirstName">First Name:</label>
        <input asp-for="FirstName" type="text" class="form-control clearable" id="firstName" Placeholder="Jane">
        <span asp-validation-for="FirstName" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="LastName">Last Name:</label>
        <input asp-for="LastName" type="text" class="form-control clearable" id="lastName" Placeholder="Doe">
        <span asp-validation-for="LastName" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Zip">Zip Code:</label>
        <input asp-for="Zip" type="text" class="form-control clearable" id="zipCode" Placeholder="55555">
        <span asp-validation-for="Zip" class="text-danger"></span>
    </div>
    <div class="form-group">
        <input type="submit" value="Search" class="btn btn-default" id="search" />
    </div>
</form>

然后是在搜索功能上绑定模型的代码:

public async Task<IActionResult> Search([Bind("FirstName, LastName, Zip")] Consumer consumer)
    {
        // Code....
    }

有没有办法动态绑定文本输入的输入id =&#34; id&#34;根据下拉菜单选择?提前谢谢。

1 个答案:

答案 0 :(得分:1)

有两种选择:

  1. 将所有字段渲染到页面(first,last,zip等),然后使用JavaScript根据下拉列表中的选择隐藏/显示这些字段。例如,如果您选择&#34;名字&#34;,则显示FirstName输入并隐藏其他输入。然后,用户在该输入中输入他们的关键字,当他们发布时,它会自然地绑定到FirstName

  2. 发布下拉列表的值和通用文本输入。在您的操作中,您只需打开下拉列表的值并查询正确的属性:

    IQueryable<Foo> query = db.Foos;
    
    switch (model.MyDropDownSelection)
    {
        case "FirstName":
            query = query.Where(x => x.FirstName.Contains(keyword));
            break;
        // etc.
    }
    
相关问题