【问题标题】:How do I fill a drop down-list based on selection by another drop-down list ASP.NET如何根据另一个下拉列表 ASP.NET 的选择填充下拉列表
【发布时间】:2020-11-11 00:03:35
【问题描述】:

我有两个下拉列表,我正在尝试创建一个动态下拉列表,用户从下拉列表中选择偏好类型,并且员工偏好值下拉列表的输入将显示用户选择的不同偏好类型的选择。

例如;用户在偏好类型中选择“天”。 Preference Value 下拉列表将显示带有“Monday,Tuesday,Wednesday”的硬编码选项列表

或

用户在偏好类型中选择“分支位置”。 偏好值下拉列表将显示带有“北、南、东、西”的硬编码选项列表

How it looks like now

我当前的代码是这样的。我现在正在使用 StaffPreferenceModel 来获取和设置视图页面中的所有项目。我不确定如何为每个不同的选择创建一个动态下拉列表。

员工偏好模型

public class StaffPreferenceModel
{
    [Key]
    [Display(Name = "Staff Preference ID")]
    public Guid StaffPreferenceID { get; set; }



    [Display(Name = "Preference Type ID")]
    public Guid PreferenceTypeID { get; set; }

    [ForeignKey("PreferenceTypeID")]
    public PreferenceTypeModel PreferenceTypes { get; set; }



    [Required(ErrorMessage = "Please Enter Staff Preference Status ..")]
    [Display(Name = "Staff Preference Value")]
    public string StaffPreferenceValue { get; set; }



    [Required(ErrorMessage = "Please Enter Prefered Date ..")]
    [Display(Name = "Staff Preference Date")]
    [DataType(DataType.Date)]
    public DateTime StaffPreferenceSetDate { get; set; }



    [Display(Name = "Branch Zone ID")]
    public Guid BranchZoneID { get; set; }
    [ForeignKey("BranchZoneID")]
    public BranchZoneModel BranchZones { get; set; }



    [Display(Name = "Staff ID")]
    public Guid StaffID { get; set; }
    [ForeignKey("StaffID")]
    public StaffModel Staffs { get; set; }



    [Display(Name = "Work Desciption ID")]
    public Nullable<Guid> WorkDescriptionID { get; set; }
    [ForeignKey("WorkDescriptionID")]
    public WorkDescriptionModel WorkDescriptions { get; set; }

}

控制器:

 public IActionResult CreateStaffPreference()
    {

        ViewData["BranchZoneID"] = new SelectList(_context.BranchZone, "BranchZoneID", "BranchZoneName");
        ViewData["PreferenceTypeID"] = new SelectList(_context.PreferenceType, "PreferenceTypeID", "PreferenceName");
        ViewData["StaffID"] = new SelectList(_context.Staff, "StaffID", "StaffName");
        ViewData["WorkDescriptionID"] = new SelectList(_context.WorkDescription, "WorkDescriptionID", "WorkDescriptionName");
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> CreateStaffPreference([Bind("StaffPreferenceID,PreferenceTypeID,StaffPreferenceValue,StaffPreferenceSetDate,BranchZoneID,StaffID,WorkDescriptionID")] StaffPreferenceModel staffPreferenceModel)
    {
        if (ModelState.IsValid)
        {
            staffPreferenceModel.StaffPreferenceID = Guid.NewGuid();
            _context.Add(staffPreferenceModel);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(ProfilePage));
        }
        ViewData["BranchZoneID"] = new SelectList(_context.BranchZone, "BranchZoneID", "BranchZoneName", staffPreferenceModel.BranchZoneID);
        ViewData["PreferenceTypeID"] = new SelectList(_context.PreferenceType, "PreferenceTypeID", "PreferenceName", staffPreferenceModel.PreferenceTypeID);
        ViewData["StaffID"] = new SelectList(_context.Staff, "StaffID", "StaffName", staffPreferenceModel.StaffID);
        ViewData["WorkDescriptionID"] = new SelectList(_context.WorkDescription, "WorkDescriptionID", "WorkDescriptionName", staffPreferenceModel.WorkDescriptionID);
        return View(staffPreferenceModel);
    }

查看页面:

<div class="row">
    <div class="col-md-4">
        <form asp-action="CreateStaffPreference">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="PreferenceTypeID" class="control-label"></label>
                <select asp-for="PreferenceTypeID" class="form-control" asp-items="ViewBag.PreferenceTypeID"></select>
            </div>
            <div class="form-group">
                <label asp-for="StaffPreferenceValue" class="control-label"></label>
                <select asp-for="StaffPreferenceValue" class="form-control" /></select>
                <span asp-validation-for="StaffPreferenceValue" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="StaffPreferenceSetDate" class="control-label"></label>
                <input asp-for="StaffPreferenceSetDate" class="form-control" />
                <span asp-validation-for="StaffPreferenceSetDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="WorkDescriptionID" class="control-label"></label>
                <select asp-for="WorkDescriptionID" class="form-control" asp-items="ViewBag.WorkDescriptionID"></select>
            </div>
            <div class="form-group">
                <label asp-for="BranchZoneID" class="control-label"></label>
                <select asp-for="BranchZoneID" class="form-control" asp-items="ViewBag.BranchZoneID"></select>
            </div>
            <div class="form-group">
                <label asp-for="StaffID" class="control-label"></label>
                <select asp-for="StaffID" class="form-control" asp-items="ViewBag.StaffID"></select>
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <input type="submit" value="Save" class="btn btn-primary btn-block" />
                </div>
                <div class="form-group col-md-6">
                    <a asp-action="ProfilePage" class="btn btn-secondary btn-block"><i class=" fa fa-table"></i>Back to List</a>
                </div>
            </div>
        </form>
    </div>
</div>

【问题讨论】:

  • 在选择偏好类型时通过 ajax 创建一个事件句柄。获取该事件 (ActioneResult) 中的 Preference Value 下拉列表并将其返回以填充到下拉列表中。
  • 嗨,@zan berzanus,如果答案解决了您的问题,请标记它以帮助更多人。如果没有,我们或许可以继续探索解决方案。请跟进。感谢您的时间和努力。
  • @MichelleWang 嗨,我仍然无法完成此功能。我正在弄清楚!谢谢
  • 嗨,@zan berzanus,我看不到级联的需求,你的意思是下拉列表的值都来自 StaffPreferenceModel 吗?如果是这样,那就比以前容易了。
  • 切换StaffPreferenceModel的方法是什么?通过重定向页面或 Dopdownlist 级联。对 ajax 函数进行编码很重要。请详细说明更多操作逻辑,以便我们提供帮助。

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


【解决方案1】:

24/07 更新

这是迷你版的结果。

如果满足您的需求,您可以按照以下步骤完成。

  1. 型号

StaffPreferenceModel中不需要添加PreferenceType,因为它只用于显示PreferenceValue的组。

public class StaffPreferenceModel
{
    [Key]
    [Display(Name = "Staff Preference ID")]
    public Guid StaffPreferenceID { get; set; }

    [Display(Name = "Preference Value ID")]
    public Guid PreferenceValueID { get; set; }

    [ForeignKey("PreferenceValueID")]
    public PreferenceValueModel PreferenceValue { get; set; }

}

public class PreferenceTypeModel
{
    [Key]
    [Display(Name = "Preference Type ID")]
    public Guid PreferenceTypeID { get; set; }

    [Display(Name = "Preference Type")]
    public string PreferenceName { get; set; }
}

public class PreferenceValueModel
{
    [Key]
    [Display(Name = "Preference Value ID")]
    public Guid PreferenceValueID { get; set; }

    [Display(Name = "Preference Value")]
    public string Value { get; set; }

    [Display(Name = "Preference Type ID")]
    public Guid PreferenceTypeID { get; set; }

    [ForeignKey("PreferenceTypeID")]
    public PreferenceTypeModel PreferenceTypes { get; set; }
}
  1. 控制器
    public IActionResult Create()
    {
        ViewData["PreferenceTypeID"] = new SelectList(_context.PreferenceTypeModel, "PreferenceTypeID", "PreferenceName");

        //list preference values by default type
        var preferenceValues = _context.PreferenceValueModel.Where(p=>p.PreferenceTypeID == _context.PreferenceTypeModel.FirstOrDefault().PreferenceTypeID);
        ViewData["PreferenceValueID"] = new SelectList(preferenceValues, "PreferenceValueID", "Value");

        return View();
    }


    [HttpPost]
    public async Task<List<PreferenceValueModel>> GetPreferenceValues(Guid id)
    {
        var PreferenceValues = _context.PreferenceValueModel.Where(p => p.PreferenceTypeID == id).ToList();
        return PreferenceValues;
    }
  1. 查看
    <form asp-action="Create">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>


        <div class="form-group">
            <label class="control-label">PreferenceType</label>
            <select id="PreferenceType" class="form-control" asp-items="ViewBag.PreferenceTypeID"></select>
        </div>

        <div class="form-group">
            <label asp-for="PreferenceValueID" class="control-label"></label>
            <select asp-for="PreferenceValueID" class="form-control" asp-items="ViewBag.PreferenceValueID"></select>
        </div>


        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>

选中PreferenceType下拉列表时使用js获取preference values。

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">

      $(document).ready(function () {
          //Dropdownlist Selectedchange event
          $("#PreferenceType").change(function () {
              $("#PreferenceValueID").empty();
              $.ajax({
                  type: 'POST',
                  url: '@Url.Action("GetPreferenceValues")', // we are calling json method
                  dataType: 'json',
                  data: { id: $("#PreferenceType").val() },
                  success: function (states) {
                      // states contains the JSON formatted list
                      // of states passed from the controller

                      $("#PreferenceValueID").append('<option value="' + "0" + '">' + "Select PreferenceValue" + '</option>');
                      debugger;
                      $.each(states, function (i, state) {
                          $("#PreferenceValueID").append('<option value="' + state.preferenceValueID + '">' + state.value + '</option>');
                          // here we are adding option for States
                      });

                  },
                  error: function (ex) {
                      alert('Failed to retrieve states.' + ex);
                  }
              });
              return false;
          })
      });
</script>


在 ASP.Net 中将 DropDownList 与另一个 DropDownList 级联。

请尝试阅读此article,如果您在MVC 中使用razor pages,请阅读this 文章。

主要步骤:

  1. 创建实体数据模型(Preference 和StaffPreference)

  2. 添加视图模型 (PreferenceView)

    public class PreferenceView
     {
         public int PreferenceId { get; set; }
         public List<Preference> PreferenceList { get; set; }
         public List<StaffPreference> StaffPreferenceList { get; set; }
     }
    
  3. 创建 action 以返回 view 和 PreferenceView。
    创建 GetStaffPreferenceByType 方法以按类型返回 StaffPreferenceList。

  4. 添加用于绑定状态下拉列表的 jQuery Ajax 脚本。

【讨论】:

  • 非常感谢这对我帮助很大,很抱歉回复晚了!但是我已经尝试过了,它确实有效,非常有帮助。干杯!
  • 您好代码有效,我需要询问是否必须在 SQL 数据库中为“首选项值”创建另一个单独的表,因为当我尝试转到页面时出现错误,它说:“ SqlException:无效的对象名称'PreferenceValue'。”
  • 我认为没有必要创建新表。从 PreferenceValueModel 中,我们可以看到“Value”是数据库中的真实对象名称,而不是“PreferenceValue”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
相关资源
最近更新 更多