简体   繁体   English

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

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

I have two drop-down lists and I am trying to make a dynamic drop-down list where the user selects the Preference Type from the drop-down list and the input for the Staff Preference Value drop-down list will display the selections for the different Preference Type that the User chooses.我有两个下拉列表,我正在尝试创建一个动态下拉列表,其中用户从下拉列表中选择偏好类型,并且员工偏好值下拉列表的输入将显示选择用户选择的不同偏好类型。

For example;例如; User chooses "Days" in the Preference Type.用户在偏好类型中选择“天”。 Preference Value drop-down list will display hard coded option list with "Monday,Tuesday,Wednesday" Preference Value 下拉列表将显示带有“Monday,Tuesday,Wednesday”的硬编码选项列表

OR或者

User chooses "Branch Location" in the Preference Type.用户在偏好类型中选择“分支位置”。 Preference Value drop-down list will display hard coded option list with "North, South, East, West"首选项值下拉列表将显示带有“北、南、东、西”的硬编码选项列表

How it looks like now现在的样子

My current code is like this.我现在的代码是这样的。 I am using a StaffPreferenceModel to get and set all the items that are in the view page right now.我现在正在使用 StaffPreferenceModel 来获取和设置视图页面中的所有项目。 I am not sure how to make a dynamic drop-down list for each of the different selections.我不确定如何为每个不同的选择创建一个动态下拉列表。

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: 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);
    }

View Page:查看页面:

<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>

UPDATE 24/07更新 24/07

Here is the result of mini version.这是迷你版的结果。 在此处输入图像描述

If it meets your needs, you could follow the steps below to accomplish it.如果它满足您的需求,您可以按照以下步骤来完成它。

  1. Model Model

There's no need to add PreferenceType in StaffPreferenceModel because it's only used to display the group of PreferenceValue . 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 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. View看法
    <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>

Use js to get preference values when PreferenceType dropdownlist selected .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>


Cascading a DropDownList with another DropDownList in ASP.Net.在 ASP.Net 中将DropDownList与另一个DropDownList级联。

Please try to read this article and if you are using razor pages in MVC , read this article.请尝试阅读这篇文章,如果你在MVC中使用razor pages ,请阅读这篇文章。

The main steps:主要步骤:

  1. Create Entity Data Model ( Preference and StaffPreference )创建实体数据 ModelPreferenceStaffPreference

  2. Adding View Model ( PreferenceView )添加视图 Model ( PreferenceView )

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

  4. Adding jQuery Ajax script for binding State dropdownlist.添加 jQuery Ajax 脚本以绑定 State 下拉列表。

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

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