html 从列表中提取与从下拉列表中选取的项目匹配的数据(Javascript + asp.net)

qmelpv7a  于 2022-12-09  发布在  Java
关注(0)|答案(1)|浏览(150)

我正在使用asp.net剃刀页面。我正在使用数据库中的数据创建列表。例如,此列表包含UserId、UserName、Education和Location等信息。在我的页面上,我希望有一个显示UserName的下拉框,当用户单击下拉框中的值时,此特定用户的匹配Education和Location将显示在两个相应的文本框中。
enter image description here
现在,我的视图中有以下代码,但它只允许我查看选择的值,而不允许查看与此用户关联的教育程度和位置值:

<body>
    <div>
        Select User: @Html.DropDownListFor(m => m.UserId, new SelectList(Model.usersinfo, "UserId", "UserName"), "Select User")<br /><br />
        Selected Text: <label id="lbltxt"></label><br /><br />
        Selected Value: <label id="lblid"></label>
    </div>
    <script type="text/javascript">

        $(function () {
       //Dropdownlist Selectedchange event
        $('#UserId').change(function () {
        // Get Dropdownlist seleted item text
        $("#lbltxt").text($("#UserId option:selected").text());
        // Get Dropdownlist selected item value
        $("#lblid").text($("#UserId").val());

        })
        })
    </script>
</body>
afdcj2ne

afdcj2ne1#

这是我的解决方法:
首先,我有一个UserModel,它定义了您提到的属性。然后,我的控制器准备数据如下:

public IActionResult Privacy()
        {
            List<UserModel> list = new List<UserModel> { 
                new UserModel{ UserId = 1, UserName="user1", Education="primary", Location="steet1"},
                new UserModel{ UserId = 2, UserName="user2", Education="middle", Location="steet2"}
            };
            ViewData["dropdown"] = list;
            return View();
        }

下面是cshtml文件:

@model WebAppMvcJwt.Models.UserModel

<div>
    <select asp-for="@Model.UserId" asp-items="(@ViewData["dropdown"] as IEnumerable<SelectListItem>)" id="UserId" class="form-control ">
        <span asp-validation-for="@Model.UserId"></span>
        @foreach (var item in @ViewData["dropdown"] as IEnumerable<UserModel>)
        {
            <option value="@item.UserId&&@item.Education&&@item.Location">@item.UserName</option>

        }
    </select>
    <input id="education" type="text" />
    <input id="location" type="text" />
</div>

@section Scripts{
    <script>
        $("#UserId").change(function () {
            var selectedid = $("#UserId option:selected").val().split("&&");
            var education = selectedid[1];
            var location = selectedid[2];
            $('#education').val(education);
            $('#location').val(location);
        });
    </script>
}

相关问题