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

Razor Page中通过下拉框自动填充SWIS文本框值的实现求助

解决方案

第一步:修正后端CreateModel代码

先清理冗余代码,确保市政数据正确加载,同时修复OnPost中的重复添加问题:

using Referrals.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Referrals.Model;
using Microsoft.EntityFrameworkCore;

namespace Referrals.Pages.Officials;

[BindProperties]
public class CreateModel : PageModel
{
    private readonly ApplicationDbContext _db;
    public Official Official { get; set; }
    public IEnumerable<Municipality> DisplayMuniName { get; set; }

    public CreateModel(ApplicationDbContext db)
    {
        _db = db;
    }

    public async Task OnGet()
    {
        // 直接加载排序后的市政数据,移除无用查询
        DisplayMuniName = await _db.Municipality.OrderBy(x => x.Name).ToListAsync();
    }

    public async Task<IActionResult> OnPost()
    {
        if (ModelState.IsValid)
        {
            // 移除重复的Add调用,仅保留异步添加
            await _db.Official.AddAsync(Official);
            await _db.SaveChangesAsync();
            TempData["success"] = "Official added successfully.";
            return RedirectToPage("Index");
        }
        // 验证失败时重新加载市政数据,避免下拉框为空
        DisplayMuniName = await _db.Municipality.OrderBy(x => x.Name).ToListAsync();
        return Page();
    }
}

第二步:前端实现自动填充逻辑

在页面中添加JavaScript监听下拉框变化,根据选中的MuniName匹配对应SWIS值:

<td style="width: 30%">
     <div class="mb-3">
          <label asp-for="Official.MuniName"></label>
          <select asp-for="Official.MuniName" id="Select1" class="form-select" asp-items="@(new SelectList(Model.DisplayMuniName,"Name", "Name"))">
              <option value="" selected disabled>---Select Municipality---</option>
          </select>
     </div>
</td>
<td style="width: 10%">
     <div class="mb-3">
          <label asp-for="Official.SWIS"></label>
          <input asp-for="Official.SWIS" class="form-control" id="swisInput" />
          <span asp-validation-for="Official.SWIS" class="text-danger"></span>
     </div>
</td>

<!-- 在页面末尾添加脚本 -->
<script>
    // 将后端传递的市政数据转为可操作的JSON对象
    const municipalities = @Html.Raw(Json.Serialize(Model.DisplayMuniName));
    
    // 获取页面元素
    const muniSelect = document.getElementById('Select1');
    const swisInput = document.getElementById('swisInput');
    
    // 监听下拉框选择事件
    muniSelect.addEventListener('change', function() {
        const selectedName = this.value;
        // 清空输入框如果未选择
        if (!selectedName) {
            swisInput.value = '';
            return;
        }
        // 匹配选中的市政数据,填充SWIS值
        const matchedMuni = municipalities.find(muni => muni.Name === selectedName);
        if (matchedMuni) {
            swisInput.value = matchedMuni.SWIS;
        }
    });
</script>

关键说明

  • 不需要使用foreach循环,前端通过find方法直接匹配选中项,逻辑更简洁高效。
  • 此方案将市政数据直接渲染到页面中,适合数据量不大的场景;如果数据量庞大,可改为通过AJAX调用后端接口获取对应SWIS值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:05:13