繁体   English   中英

如何根据另一个下拉列表 ASP.NET 的选择填充下拉列表

[英]How do I fill a drop down-list based on selection by another drop-down list ASP.NET

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

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

或者

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

现在的样子

我现在的代码是这样的。 我现在正在使用 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; }

}

Controller:

 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>

更新 24/07

这是迷你版的结果。 在此处输入图像描述

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

  1. Model

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. Controller
    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 dropdownlist selected 时使用 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级联。

请尝试阅读这篇文章,如果你在MVC中使用razor pages ,请阅读这篇文章。

主要步骤:

  1. 创建实体数据 ModelPreferenceStaffPreference

  2. 添加视图 Model ( PreferenceView )

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

  4. 添加 jQuery Ajax 脚本以绑定 State 下拉列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM