In an ASP.NET MVC application, binding dynamic data to a dropdown list involves fetching data from a database and populating the dropdown list on the client side using jQuery. Here's how you can achieve this.

I have home controller and a method named with GetCity() , which takes the StateId and return the City data .
Step 1 : Add below method to your controller

 public JsonResult GetCity(string Id)
        {
            try
            {
                string[,] Param = new string[,]
                    {
                        {"@Id",Id.Trim()},
                        {"@Type", "City"}
                    };

                DataTable dt_State = CommonMethod.ExecuteProcedure(Param, "USP_GetStateAndCity");
                List<SelectListItem> states = new List<SelectListItem>();
                if (dt_State.Rows.Count > 0)
                {
                    foreach (DataRow row in dt_State.Rows)
                    {
                        states.Add(new SelectListItem
                        {
                            Value = row["CityId"].ToString(),
                            Text = row["CityName"].ToString()
                        });
                    }
                }
                return Json(new { Status = "1", States = states }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Status = "0", Message = CommonMethod.Message()}, JsonRequestBehavior.AllowGet);
            }
        }

Note : In above given example where the stored procedure USP_GetStateAndCity is used to fetch city details based on the selected StateId, and the CommonMethod class with the ExecuteProcedure method is responsible for executing the stored procedure and returning data from the database.

Step 2 : Create method to execute your procedure :

 public static DataTable ExecuteProcedure(string[,] Param, string ExecuteProcedure)
    {
        try
        {
            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get("DBString"));
            SqlCommand cmd = new SqlCommand(ExecuteProcedure, con);
            cmd.CommandType = CommandType.StoredProcedure;
            for (int i = 0; i < Param.Length / 2; i++)
            {
                cmd.Parameters.AddWithValue(Param[i, 0], Param[i, 1]);
            }
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
        }
        catch (Exception ex)
        {
            throw;
        }

    }

Step 3 : Create procedure as given below  (change according to your requirement)

Create Proc USP_GetStateAndCity
(
    @Type Varchar(10),
    @Id Int
)
As
Begin
    If @Type='State'
    Begin
        Select distinct StateId,StateName from StateMaster   where CountryId=@Id order by StateName
    End
    Else
    Begin
        Select distinct CityId,CityName from CityMaster   where StateId=@Id order by CityName
    End
End



Step 4 : Now call GetCity() method in jQuery to fetch the data.

function GetCity(CityId) {
    try {
        $.post(CommonURL + "Home/GetCity", {
            Id: CityId
        }, function (data) {
            if (data.Status == "1") {
                var cityDropdown = $("#ddlCity");
                cityDropdown.empty();
                cityDropdown.append('<option value="0">--Select City--</option>');
                $.each(data.States, function (index, state) {
                    cityDropdown.append('<option value="' + state.Value + '">' + state.Text + '</option>');
                });
            } else {
                showToast("Error", "Failed to load states:", "");
            }
        });
    } catch (e) {
        showToast("Error", "Failed to load states.", "");
    }
}

Note : The jQuery code will be triggered onchange of the State dropdown. When the user selects a state, an request will be made to fetch the cities associated with that state. The city dropdown will then be dynamically populated with the returned data based on the selected StateId. If no state is selected, the city dropdown will be reset to its default option.

Function Explanation:

function GetCity(CityId) {
    try {
        $.post(CommonURL + "Home/GetCity", {
            Id: CityId
        }, function (data) {
            if (data.Status == "1") {
                var cityDropdown = $("#ddlCity");
                cityDropdown.empty();  // Clear any existing options in the city dropdown
                cityDropdown.append('<option value="0">--Select City--</option>');  // Add default 'Select City' option
               
                // Loop through the States array returned from the server and append each city as an option
                $.each(data.States, function (index, state) {
                    cityDropdown.append('<option value="' + state.Value + '">' + state.Text + '</option>');
                });
            } else {
                // If the response status is not "1", show an error message
                showToast("Error", "Failed to load states:", "");
            }
        });
    } catch (e) {
        // If there's an exception, show an error message
        showToast("Error", "Failed to load states.", "");
    }
}

Explanation:

  1. Function Definition:
    GetCity(CityId) is a function that accepts a CityId parameter. This ID will likely be used to fetch related data (like states or cities) from the server.

  2. AJAX Request:

    • The function makes a POST request to the server endpoint CommonURL + "Home/GetCity", sending the CityId in the request body (Id: CityId).
    • The request is handled by the server-side action (Home/GetCity) which is expected to return a response with city/state data in JSON format.
  3. Success Callback:

    • Once the request is successful, the callback function is executed, receiving the data object returned by the server.
    • The data object is expected to have a Status field to indicate if the request was successful (in this case, Status == "1" means success).
  4. Populating Dropdown:

    • If the status is "1" (success):
      • The city dropdown (#ddlCity) is cleared using empty().
      • A default option ("--Select City--") is added to the dropdown.
      • The function then loops through the States array from the server response and appends each state as an <option> element to the dropdown. Each option uses state.Value as the value and state.Text as the displayed text.
  5. Error Handling:

    • If the Status is not "1", a toast notification is shown using showToast() to indicate that loading states failed.
    • Additionally, any errors or exceptions thrown during the process are caught by the catch block, and a generic error message is displayed through the showToast() function.

Key Points:

  • AJAX $.post: Sends a POST request to the server with CityId as data.
  • Success Handling: On a successful response, the city dropdown (#ddlCity) is populated with the returned cities/states.
  • Error Handling: If an error occurs during the request or the response status isn't "1", a toast message is displayed.

Leave a Reply

Your email address will not be published. Required fields are marked *


Talk to us?

Post your blog

F.A.Q

Frequently Asked Questions