I have two dropdownlist, One for state and another for City. Also to add extra city there is another form, which opens in the new tab.
What i want is that, when I add the extra city for the respective state from the new tab. I want to refresh the State dropdownlist so that, I can fetch the extra city added when I select the respective State from the dropdownlist.
Please see the HTML code:-
<tr>
<td class="td">Location/State</td>
<td>
<asp: DropDownList CssClass="txtfld-popup" ID="ddlState" OnSelectedIndexChanged="ddlState_SelectedIndexChanged" runat="server" AutoPostBack="true"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="RequiredFieldValidator1" ControlToValidate="ddlState" runat="server" ErrorMessage="Please enter State" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
Someone suggested to use UpdatePanel
but i was unable to use that. Please help
HTML for the city dropdown:
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlCity" runat="server" AutoPostBack="true"></asp:DropDownList>
<a id="aExtraCity" href="AddCity.aspx" runat="server">Add City</a>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlCity" runat="server" ErrorMessage="Please enter City" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
Also see the Code behind for the dropdownlist:-
public void LoadDropDowns()
{
string country = "India";
ddlCountry.SelectedValue = country;
ddlCountry.Enabled = false;
ddlMinExpYr.DataSource = Years;
ddlMinExpYr.DataBind();
ddlMaxExpYr.DataSource = Years;
ddlMaxExpYr.DataBind();
//populate states
var states = _helper.GetStates(country);
states.Insert(0, "--Select--");
ddlState.DataSource = states;
ddlState.DataBind();
}
AddCity code behind:-
protected void btnAddDropDown_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_CityforLocation";
cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = 0;
cmd.Parameters.Add("@CountryName", SqlDbType.VarChar).Value = "India";
cmd.Parameters.Add("@StateName", SqlDbType.VarChar).Value = ddlState.SelectedItem.ToString();
cmd.Parameters.Add("@CityName", SqlDbType.VarChar).Value = txtCity.Text.Trim();
cmd.Connection = con;
try
{
cmd.ExecuteNonQuery();
// BindContrydropdown();
}
catch (Exception ex)
{
Response.Write(ex.Message);//You Can Haave Messagebox here
}
finally
{
con.Close();
}
}
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ScriptKey", "alert('Your City has been Added.');window.location='Career_Job.aspx'; ", true);
}
There are methods of triggering a server side refresh of an update panel from JavaScript which would eliminate that problem though. The other option would be to use an HTML drop down instead of the ASP one of course or to disable event validation (not suggested).
To add a dropdown to a button, simply wrap the button and dropdown menu in a . btn-group. You can also use <span class = "caret"></span> to act as an indicator that the button is a dropdown.
The DropDownList control is a web server element that creates the drop-down menu and lets users select a single item from various options. You can add any number of items to the DropDownList.
Updating the City drop down list without any events fired from the client can be done by implementing long polling or using frame works such as SignalR. A very similar question was asked and answered here.
Here is an example in web forms using SignalR. Make sure you download and install Microsoft.AspNet.SignalR from NuGet.
Startup.cs changes
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;
using Owin;
public partial class Startup {
public void Configuration(IAppBuilder app)
{
// map signalr hubs
app.Map("/city", map => {
map.UseCors(CorsOptions.AllowAll);
var config = new HubConfiguration() {
EnableJSONP = true,
EnableJavaScriptProxies = false
};
config.EnableDetailedErrors = true;
map.RunSignalR(config);
});
ConfigureAuth(app);
}
}
Here is a simple Hub which would take care of updating all subscribed clients with any new cities added.
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
public class CityHub : Hub {
// will be called from client side to send new city
// data to the client with drop down list
public Task SendNewCity(string cityName)
{
// dynamically typed method to update all clients
return Clients.All.NewCityNotification(cityName);
}
}
Here is a helper js script to create the connections to the Hub. Please note, this piece of code is from another example and I have included the license as well. Just create a JavaScript file somewhere in your solution and add this script. You will be using it on the client. I added this under ~/Scripts/app.js
~/Scripts/app.js
/*!
* ASP.NET SignalR JavaScript Library v2.0.0
* http://signalr.net/
*
* Copyright Microsoft Open Technologies, Inc. All rights reserved.
* Licensed under the Apache 2.0
* https://github.com/SignalR/SignalR/blob/master/LICENSE.md
*
*/
/// <reference path="..\..\SignalR.Client.JS\Scripts\jquery-1.6.4.js" />
/// <reference path="jquery.signalR.js" />
(function ($, window, undefined) {
/// <param name="$" type="jQuery" />
"use strict";
if (typeof ($.signalR) !== "function") {
throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/js.");
}
var signalR = $.signalR;
function makeProxyCallback(hub, callback) {
return function () {
// Call the client hub method
callback.apply(hub, $.makeArray(arguments));
};
}
function registerHubProxies(instance, shouldSubscribe) {
var key, hub, memberKey, memberValue, subscriptionMethod;
for (key in instance) {
if (instance.hasOwnProperty(key)) {
hub = instance[key];
if (!(hub.hubName)) {
// Not a client hub
continue;
}
if (shouldSubscribe) {
// We want to subscribe to the hub events
subscriptionMethod = hub.on;
} else {
// We want to unsubscribe from the hub events
subscriptionMethod = hub.off;
}
// Loop through all members on the hub and find client hub functions to subscribe/unsubscribe
for (memberKey in hub.client) {
if (hub.client.hasOwnProperty(memberKey)) {
memberValue = hub.client[memberKey];
if (!$.isFunction(memberValue)) {
// Not a client hub function
continue;
}
subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue));
}
}
}
}
}
$.hubConnection.prototype.createHubProxies = function () {
var proxies = {};
this.starting(function () {
// Register the hub proxies as subscribed
// (instance, shouldSubscribe)
registerHubProxies(proxies, true);
this._registerSubscribedHubs();
}).disconnected(function () {
// Unsubscribe all hub proxies when we "disconnect". This is to ensure that we do not re-add functional call backs.
// (instance, shouldSubscribe)
registerHubProxies(proxies, false);
});
proxies.cityHub = this.createHubProxy('cityHub');
proxies.cityHub.client = {};
proxies.cityHub.server = {
sendNewCity: function (message) {
/// <summary>Calls the Send method on the server-side ChatHub hub. Returns a jQuery.Deferred() promise.</summary>
/// <param name=\"message\" type=\"String\">Server side type is System.String</param>
return proxies.cityHub.invoke.apply(proxies.cityHub, $.merge(["SendNewCity"], $.makeArray(arguments)));
}
};
return proxies;
};
signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
$.extend(signalR, signalR.hub.createHubProxies());
}(window.jQuery, window));
Here is a simple page where you have a single text input and a button to add a new City. Note, that you will need jquery, jquery.signalR, and the script above (/Scripts/app.js).
AddNewCity.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../../Scripts/jquery-1.10.2.min.js"></script>
<script src="../../Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="../../Scripts/app.js"></script>
<script>
$(function () {
var cityHub = $.connection.cityHub;
$.connection.hub.url = "/city";
$.connection.hub.logging = true;
$.connection.hub.start().done(function () {
$("#addCity").click(function () {
cityHub.server.sendNewCity($("#cityName").val())
.fail(function (err) {
alert(err);
});
$("#text").val("").focus();
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id ="cityName" type="text" placeholder="City name"/>
<input id="addCity" type="button" value="Add City"/>
</div>
</form>
</body>
</html>
Here is a separate page where your City drop down list exists. This separate page will automatically be updated once you add a new city from the Add City page.
CityDropDownList.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../../Scripts/jquery-1.10.2.min.js"></script>
<script src="../../Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="../../Scripts/app.js"></script>
<script>
$(function () {
var cityHub = $.connection.cityHub;
$.connection.hub.url = "/city";
$.connection.hub.logging = true;
cityHub.client.newCityNotification = newCityNotification;
$.connection.hub.start().done(function () {
});
function newCityNotification(city) {
$("#cityddl").append($(getCityOptionItem(city)));
}
function getCityOptionItem(city) {
return "<option>" + city + "</option>";
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="cityddl">
<option id="0">Existing City</option>
</select>
</div>
</form>
</body>
</html>
I have tested this myself and all seems to be working. You should end up with 2 separate pages, AddNewCity.aspx and CityDropDownList.aspx. Once you add a new city from AddNewCity.aspx, that value will get sent to the CityDropDownList.aspx and update the drop down list with the new city.
Please make sure to remove the down vote once you've given this a try.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With