简体   繁体   中英

How to bind a dropdown list according to another dropdown selected value using ajax in aspnet webforms

We have a .aspx page with two HTML SELECT element and we want to load countries in one dropdownlist and load cities of a country in the other.

we are using entity framework to access data.

I tried PageMethods and &Ajax but I could not access my city dropdown from within a static web method. this is what we have so far:

<!-- Signup.aspx-->
<select id="cmb_Region" runat="server" onchange="GetCitiesOfRegion();" datatextfield="region_title" datavaluefield="region_id"></select>
<select runat="server" id="cmb_City" datatextfield="city_title" datavaluefield="city_id" class="ui dropdown"></select>

<script type="text/javascript">
    function GetCitiesOfRegion(regionId)
    {
        $.ajax({
            url:"Signup.aspx/GetCities",
            type:"POST",
            data:'{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                alert("success");
            }
            });
    }
</script>

and this is code-behind code:

//Signup.aspx.cs
[WebMethod]
    public static List<City> GetCities(int RegionId)
    {
        behbimeh_informationEntities db = new behbimeh_informationEntities();
        return db.City.Where(i => i.region_id == RegionId).ToList();
    }

Actually the code is not correct and I dont know how to pass the cmb_region selected value to the webmethod? and I dont know how to bind the cmb_city to the returned List of cities.

please share your knowledge. thanks...

To get cmb_Region value

var regionId = $('#<%= cmb_Region.ClientID %>').val();

To get cities by region and bind at client side

[WebMethod]
public static string GetCities(int RegionId)
{
    behbimeh_informationEntities db = new behbimeh_informationEntities();
    var cities=  db.City.Where(i => i.region_id == RegionId).Select(item=>new { item.ValueField, item.TextField }).ToList();
    return Newtonsoft.Json.JsonConvert.SerializeObject(cities);
}
<script type="text/javascript">
function GetCitiesOfRegion(regionId)
{
    $.ajax({
        url:"Signup.aspx/GetCities",
        type:"POST",
        data:'{"RegionId":'+regionId+'}',           
        success: function (r) {
            var cities=JSON.parse(r.d);
            var citiesOptions="";
            for(var i=0;i<cities.length;i++){
                 citiesOptions+='<option value="'+cities[i].Value+'">'+cities[i].Text+'</option>';
            }
            $('#<%= cmb_City.ClientID %>').html(citiesOptions);
        }
        });
}

first you will need to clear the existing data, like so:

$('#cmb_city').empty();

next, you need to load the returned list to your ddl.

$.ajax({
        url:"Signup.aspx/GetCities",
        type:"POST",
        data:'{"RegionId":'+$('#cmb_Region').val()+'}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
               $.each(r, function() { 
                  $('#cmb_city').append($('<option>').text(this.Name).attr('value', this.Id));
               });
            }
        });

where Name and Id are your text and value fields respectively.

you will also probably need to send the selected region.

Here is your answer like how to bind data from database using Ajax in php

<!-- edit.php -->
<?php
include("config.php");
$id=$_REQUEST['id'];
echo $id;
$query=mysqli_query($con,"SELECT * FROM register r
INNER JOIN country c ON r.cuid = c.cuid
INNER JOIN state s ON r.sid = s.sid
INNER JOIN city ct ON r.cid = ct.cid where id='$id'");

while($r=mysqli_fetch_array($query))
{

     $fn=$r['firstname'];
     $add=$r['address'];
     $gn=$r['gender'];
     $hobby=$r['hobby'];
     $h=explode(',',$hobby);
     $q=array('reading','traveling','cricket','drawing');
     $country=$r['cuid'];
     $state=$r['sid'];
     $city=$r['cid'];
     echo $gn;
     $edu= $r['education'];
     $email=$r['email'];
     $pass=$r['password'];
     $conpass=$r['conpassword'];
     $phno=$r['phoneno'];
}

?>
<html>
<head>
    <script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){

    $('#country').on('change',function(){
        var countryID = $(this).val();
        if(countryID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'cuid='+countryID,
                success:function(html){
                    $('#state').html(html);
                    $('#city').html(html); 
                }
            }); 
        }else{
            $('#state').html(html);
            $('#city').html(html); 
        }
    });

    $('#state').on('change',function(){
        var stateID = $(this).val();
        if(stateID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'sid='+stateID,
                success:function(html){
                    $('#city').html(html);
                }
            }); 
        }else{
            $('#city').html(html); 
        }
    });
});
</script>
</head>
    <body>
        <form method="post" action="update.php">
            <table border="1" align="center">
            <caption>Edit user data</caption>
            <tr>
                <td>First name</td>
                <td><input type="text" name="fn" value="<?php echo $fn;?>"></td>
            </tr>
            <tr>
                <td>Address</td>
                <td><input type="text" name="add" value="<?php echo $add;?>"></td>
            </tr>
            <tr>
                <td>Gender</td>
                <td><input type="radio" name="gn" value="male" <?php echo ($gn=='male')?'checked':'' ; ?> size="17">Male
                <input type="radio" name="gn" value="female" <?php echo ($gn=='female')?'checked':'' ; ?> size="17">Female
                </td>
            </tr>
            <tr>
                <td>Hobby</td>
                <td><input type="checkbox" name="hobby[]" value="reading" <?php if(in_array('reading',$h)){echo ("checked:'checked'");}?> >reading
                <input type="checkbox" name="hobby[]" value="traveling" <?php if(in_array('traveling',$h)){echo ("checked:'checked'");}?> >traveling
                <input type="checkbox" name="hobby[]" value="cricket" <?php if(in_array('cricket',$h)){echo ("checked:'checked'");}?> >cricket
                <input type="checkbox" name="hobby[]" value="drawing" <?php if(in_array('drawing',$h)){echo ("checked:'checked'");}?> >drawing</td>
            </tr>
            <?php
            $query = mysqli_query($con,"SELECT * FROM country");

            //Count total number of rows
            $rowCount = mysqli_num_rows($query);
            ?>
            <td>Country</td>
            <td><select name="country" id="country">
                <option value="<?php echo $country;?>"><?php echo $country;?></option>
                <?php
                if($rowCount > 0)
                {
                    while($row = mysqli_fetch_array($query))
                    { 
                        echo '<option value="'.$row['cuid'].'">'.$row['country'].'</option>';
                    }
                }
                else
                {
                    echo '<option value="">Country not available</option>';
                }
                ?>
            </select>
            </td></tr>
            <tr>
            <td>State</td>
            <td>
            <select name="state" id="state">
                <option value="<?php echo $state;?>"><?php echo $state;?></option>

            </select>
            </td></tr>
            <tr>
            <td>City</td>
            <td>
            <select name="city" id="city">
                <option value="<?php echo $city;?>"><?php echo $city;?></option>

            </select>
            </td>
            </tr>
            <tr>
                <td>Education</td>
                <td><input type="text" name="edu" value="<?php echo $edu;?>"></td>
            </tr>
                <td>Email</td>
                <td><input type="text" name="email" value="<?php echo $email;?>"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="text" name="pass" value="<?php echo $pass;?>"></td>
            </tr>
            <tr>
                <td>Confirm password</td>
                <td><input type="text" name="conpass" value="<?php echo $conpass;?>"></td>
            </tr>
            <tr>
                <td>Phone no</td>
                <td><input type="text" name="phno" value="<?php echo $phno;?>"></td>
            </tr>
            <tr>
                <td><input type="hidden" name="id" value="<?php echo $id;?>">
                <input type="submit" name="update" value="update"></td>
            </tr>
            </table>
        </form>
    </body>
</html>


--------------------

<!--ajaxData.php-->
<?php
//Include database configuration file
include("config.php");

if(isset($_POST["cuid"]) && !empty($_POST["cuid"]))
{
    //Get all state data
    $query = mysqli_query($con,"SELECT * FROM state WHERE cuid = ".$_POST['cuid']."");

    //Count total number of rows
    $rowCount = mysqli_num_rows($query);

    //Display states list
    if($rowCount > 0)
    {
        echo '<option value="">Select state</option>';
        while($row =  mysqli_fetch_array($query))
        { 
            echo '<option value="'.$row['sid'].'">'.$row['state'].'</option>';
        }
    }
    else
    {
        echo '<option value="">State not available</option>';
    }
}

if(isset($_POST["sid"]) && !empty($_POST["sid"]))
{
    //Get all city data
    $query = mysqli_query($con,"SELECT * FROM city WHERE sid =".$_POST['sid']."");

    //Count total number of rows
    $rowCount = mysqli_num_rows($query);

    //Display cities list
    if($rowCount > 0)
    {
        echo '<option value="">Select city</option>';
        while($row = mysqli_fetch_array($query))
        { 
            echo '<option value="'.$row['cid'].'">'.$row['city'].'</option>';
        }
    }
    else
    {
        echo '<option value="">City not available</option>';
    }
}
?>

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