You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Razor Pages实现下拉框选用户后联动显示教育及位置信息

解决ASP.NET Razor Pages下拉框选择用户后显示关联教育和位置信息的问题

方案一:前端直接读取自定义属性(适合数据量小、非敏感场景)

原来的DropDownListFor仅支持传递Value和Text,我们需要手动生成<option>标签,将Education和Location存入自定义data-*属性中,前端选择时直接读取这些属性:

<body>
    <div>
        Select User: 
        <select asp-for="UserId" id="UserId">
            <option value="">Select User</option>
            @foreach (var user in Model.usersinfo)
            {
                <option value="@user.UserId" 
                        data-education="@user.Education" 
                        data-location="@user.Location">
                    @user.UserName
                </option>
            }
        </select><br /><br />
        
        Selected Text: <label id="lbltxt"></label><br /><br />
        Selected Value: <label id="lblid"></label><br /><br />
        
        <!-- 添加显示教育和位置的只读文本框 -->
        Education: <input type="text" id="txtEducation" readonly /><br /><br />
        Location: <input type="text" id="txtLocation" readonly />
    </div>
    <script type="text/javascript">
        $(function () {
            $('#UserId').change(function () {
                var selectedOption = $(this).find('option:selected');
                // 更新选中项的文本和值显示
                $("#lbltxt").text(selectedOption.text());
                $("#lblid").text(selectedOption.val());
                
                // 读取自定义属性并填充文本框
                $("#txtEducation").val(selectedOption.data('education'));
                $("#txtLocation").val(selectedOption.data('location'));
            })
        })
    </script>
</body>

说明:这种方式实现简单,无需额外请求,但所有用户的教育、位置信息会暴露在页面源码中,不适合敏感数据场景。


方案二:通过AJAX请求后端获取数据(适合敏感数据、数据量大场景)

步骤1:后端添加用户详情接口

在你的PageModel类中,新增一个Get方法用于返回指定用户的教育和位置信息:

public class YourPageModel : PageModel
{
    // 从数据库获取的用户列表
    public List<UserInfo> usersinfo { get; set; }

    // 页面加载时初始化用户数据(实际替换为数据库查询逻辑)
    public void OnGet()
    {
        usersinfo = new List<UserInfo>
        {
            new UserInfo { UserId = 1, UserName = "张三", Education = "本科", Location = "北京" },
            new UserInfo { UserId = 2, UserName = "李四", Education = "硕士", Location = "上海" }
        };
    }

    // 提供给AJAX调用的接口
    public IActionResult OnGetGetUserDetails(int userId)
    {
        var user = usersinfo.FirstOrDefault(u => u.UserId == userId);
        if (user == null)
        {
            return new JsonResult(new { success = false });
        }
        return new JsonResult(new 
        { 
            success = true,
            education = user.Education,
            location = user.Location
        });
    }

    // 用户信息实体类
    public class UserInfo
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Education { get; set; }
        public string Location { get; set; }
    }
}

步骤2:前端修改为AJAX请求逻辑

保留原下拉框,修改脚本逻辑,选择用户时向后端请求对应数据:

<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><br /><br />
        
        Education: <input type="text" id="txtEducation" readonly /><br /><br />
        Location: <input type="text" id="txtLocation" readonly />
    </div>
    <!-- 添加Razor Pages必填的防伪造令牌 -->
    @Html.AntiForgeryToken()
    <script type="text/javascript">
        $(function () {
            $('#UserId').change(function () {
                var userId = $(this).val();
                var selectedOption = $(this).find('option:selected');
                
                $("#lbltxt").text(selectedOption.text());
                $("#lblid").text(userId);

                // 未选择用户时清空文本框
                if (!userId) {
                    $("#txtEducation").val('');
                    $("#txtLocation").val('');
                    return;
                }

                // 发送AJAX请求获取用户详情
                $.ajax({
                    url: '/YourPageName?handler=GetUserDetails', // 替换为你的实际页面名称(如/Index)
                    data: { userId: userId },
                    type: 'GET',
                    headers: {
                        // 携带防伪造令牌避免400错误
                        RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function (response) {
                        if (response.success) {
                            $("#txtEducation").val(response.education);
                            $("#txtLocation").val(response.location);
                        } else {
                            $("#txtEducation").val('');
                            $("#txtLocation").val('');
                        }
                    },
                    error: function () {
                        alert('获取用户信息失败,请重试');
                    }
                });
            })
        })
    </script>
</body>

说明:这种方式不会暴露敏感数据,安全性更高,但需要额外的HTTP请求。注意替换代码中的YourPageName为你的实际页面路径。


内容的提问来源于stack exchange,提问作者Marfa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:25:30