简体   繁体   中英

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"

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

 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

Here is the result of mini version. 在此处输入图像描述

If it meets your needs, you could follow the steps below to accomplish it.

  1. Model

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

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

Please try to read this article and if you are using razor pages in MVC , read this article.

The main steps:

  1. Create Entity Data Model ( Preference and StaffPreference )

  2. Adding View 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 .
    Create a GetStaffPreferenceByType method to return StaffPreferenceList by type.

  4. Adding jQuery Ajax script for binding State dropdownlist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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