我有两个下拉列表,一个用于州,另一个用于城市。此外,为了添加额外的城市,还有另一种形式,它会在新标签页中打开。
我想要的是,当我从新选项卡中为各自的州添加额外的城市时。我想刷新 State 下拉列表,这样当我从下拉列表中选择相应的 State 时,我可以获取添加的额外城市。
请看HTML代码:-
<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>
有人建议使用 UpdatePanel
但我无法使用它。请帮忙
城市下拉列表的 HTML:
<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>
另请参阅下拉列表背后的代码:-
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 后面的代码:-
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);
}
最佳答案
可以通过实现长轮询或使用 SignalR 等框架作品来更新城市下拉列表,而无需从客户端触发任何事件。提出并回答了一个非常相似的问题here .
这是一个使用 SignalR 的 Web 表单示例。确保从 NuGet 下载并安装 Microsoft.AspNet.SignalR。
Startup.cs 更改
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);
}
}
这是一个简单的 Hub,它将负责更新所有订阅的客户端,添加任何新城市。
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);
}
}
这是一个帮助程序 js 脚本,用于创建与集线器的连接。请注意,这段代码来自另一个示例,我也包含了许可证。只需在您的解决方案中的某处创建一个 JavaScript 文件并添加此脚本。您将在客户端上使用它。 我在 ~/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));
这是一个简单的页面,您可以在其中输入一个文本和一个用于添加新城市的按钮。请注意,您将需要 jquery、jquery.signalR 和上面的脚本 (/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>
这是一个单独的页面,您的城市下拉列表存在于其中。一旦您从“添加城市”页面添加新城市,这个单独的页面将自动更新。
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>
我自己测试过,似乎一切正常。您应该以 2 个单独的页面结束,AddNewCity.aspx 和 CityDropDownList.aspx。从 AddNewCity.aspx 添加新城市后,该值将发送到 CityDropDownList.aspx 并使用新城市更新下拉列表。
关于c# - 在按钮上单击下拉列表以刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27943558/