Populate DropDownList from another DropDownList

后端 未结 1 1988
别跟我提以往
别跟我提以往 2021-01-07 01:41

I have two related models.

public partial class bs_delivery_type
{  
    public decimal delivery_id { get; set; }
    public decimal delivery_city_id { get;          


        
相关标签:
1条回答
  • 2021-01-07 01:56

    The following guide will show you:

    • Create a partial view
    • Takes cityid as input and outputs the delivery address list
    • Load partial view into your select

    Note: Partial view solution may be overkill in this situation, but for similar problems it is actually quite usefull.

    PartialView .cshtml

    Filename: _deliveryTypePartial.cshtml

    @model List<bs_delivery_type>
    
    @foreach(var item in Model)
    {
        <option value="@item.delivery_id">
            @item.delivery_address
        </option>
    }
    

    Controller Code for Partial View:

    public IActionResult _deliveryTypePartial(decimal city_id)
    {
        List<bs_delivery_type> model = context.bs_delivery_types.Where(row => row.delivery_city_id == delivery_city_id).ToList();
        return PartialView(model);
    }
    

    And then Finally, for your AJAX

    I notice that your two dropdownlists have identical ID's witch will cloud your javascript code and is considered bad practice, so for the purposes of this guide I will call the first dropdownlist:

    ddlcity

    Now, inside your onchange function for ddlcity:

    $('#ddldelivery').load("/ControllerName/_deliveryTypePartial?city_id=" _stateId);
    

    This should load the partial view into your second dropdown list.

    PS: As I completed this question you had already used the direct ajax method, I agree that both methods are equally suitable in this case. You can perhaps use the method outlined here if the actual objects you need to populate are a lot more complex.

    0 讨论(0)
提交回复
热议问题