我有两个下拉列表,一个用于州,另一个用于城市。此外,为了添加额外的城市,还有另一种形式,可在新标签页中打开。
我想要的是,当我从新标签添加相应州的额外城市时。我想刷新州下拉列表,这样,当我从下拉列表中选择相应的州时,我可以获取额外的城市。
请参阅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);
}
答案 0 :(得分:5)
通过实施长轮询或使用SignalR等框架工作,可以在不向客户端发出任何事件的情况下更新城市下拉列表。提出了一个非常相似的问题并回答了here。
以下是使用SignalR的网络表单中的示例。确保从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脚本,用于创建与Hub的连接。请注意,这段代码来自另一个例子,我也包含了许可证。只需在解决方案的某处创建一个JavaScript文件并添加此脚本即可。您将在客户端上使用它。 我在〜/ Scripts / app.js
下添加了这个<强>〜/脚本/ 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并使用新城市更新下拉列表。
请务必在尝试后删除投票。
答案 1 :(得分:4)
我建议你使用UpdatePanel。触发器将添加新城市的事件(可能是按钮点击)
<asp:ScriptManager runat="server" ID="sm1" EnableScriptGlobalization="true" EnableScriptLocalization="true"></asp:ScriptManager>
<asp:UpdatePanel ID="up1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="ddTest" runat="server" AutoPostBack="True" AppendDataBoundItems="true">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ButtonAdd" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
页面中的某个地方
<asp:BUtton runeat="server" id="ButtonAdd"></asp:Button>
在单击按钮事件的代码隐藏中以这种方式向ddTest
下拉列表添加元素
ddTest.Items.Add(new ListItem("CityName", "CityCode"));
通过这种方式,当您单击添加按钮时,将添加下拉列表中的新元素,并刷新UI。
答案 2 :(得分:2)
您可以打开&#34;添加城市&#34;弹出窗口中的页面(如果你不介意的话)。保存后做类似的事情
Response.Write("<script>opener.RefreshDropDown('" + id + "','" + val + "');</script>");
Response.Write("<script>window.close();</script>");
并添加一些像
这样的javascriptfunction RefreshDropDown(val,txt)
{
var opt = document.createElement("option");
var sCtrl = document.getElementById('<%= ddlCity.ClientID %>').options.add(opt);
opt.text = txt;
opt.value = val;
}