点击按钮时刷新下拉列表

7

我有两个下拉框,一个是州(State)的,另一个是城市(City)的。同时,为了添加额外的城市,有另一个表单会在新标签页中打开。

我希望的是,当我在新标签页中为相应的州添加额外的城市后,我想刷新州(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();
}

添加城市代码后端:

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);
}

我们没有看到任何实际的代码,应该怎么办?另外,知道你尝试了什么以及错误的结果会很有用... - Laurent S.
@Bartdude:请查看更新后的问题,但每当我点击刷新按钮时,它都会生成一个新的下拉列表..!! - Rahul Sutar
如果你不理解的话,我们可能需要一些后台代码(C#,VB.NET等)来至少知道你做错了什么,我认为对于任何人来说帮助你将非常困难。但我看到你已经有了3个赞,所以我可能误解了整件事情... - Laurent S.
1
@RahulSutar,你说你想刷新州下拉菜单?难道你不应该更新城市下拉列表吗? - Mairaj Ahmad
@insomnium_: 看看更新后的代码.. - Rahul Sutar
显示剩余10条评论
3个回答

5

如果不需要从客户端触发事件,可以通过实现长轮询或使用SignalR等框架来更新城市下拉列表。这里有一个非常相似的问题 here 的解答。

以下是在Web Forms中使用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脚本。请注意,这段代码来自另一个示例,我也包含了许可证。只需在解决方案中的某个位置创建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.&#10;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>

这里有一个单独的页面,包含你城市下拉列表。一旦你在“添加城市”页面上添加新城市,这个单独的页面就会自动更新。请注意保留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>

我已经亲自测试过,一切似乎都在正常运行。您应该会得到两个单独的页面:AddNewCity.aspx和CityDropDownList.aspx。从AddNewCity.aspx添加新城市后,该值将发送到CityDropDownList.aspx并使用新城市更新下拉列表。

我不想用MVC,我想用简单的.NET。 - Rahul Sutar
那个具体的例子是在MVC中(顺便说一下,这是简单的.NET),你可以在Web表单中执行相同的任务。我会很快为您发布一个示例。 - boosts
好的,我会等待并实现..!! - Rahul Sutar
这不是我想要的。你让我的代码变得更加复杂了。无论如何,感谢你的努力。我会取消踩的。 - Rahul Sutar
2
除非进行以下两个更改,否则这种解决方案是您唯一的选择。您可以将新城市的添加移动到与州和城市下拉菜单相同的页面上,或者强制用户通过单击按钮或类似事件手动刷新下拉菜单。建议使用更新面板来完成这两个更改。但是,您最初的问题明确说明了在新页面中完成添加新城市的操作。 - boosts

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界面。


我应该把按钮放在哪里?在Update Panel内部还是外部? - Rahul Sutar
它不起作用,每当我点击按钮时,它会再次生成与“State”相同的新下拉列表。 - Rahul Sutar
让我们在聊天中继续这个讨论 - Rahul Sutar
仍在生成下拉列表。 - Rahul Sutar
“is generating a dropdownlist”是什么意思?哪个是错误的行为? - faby
显示剩余20条评论

2
您可以在弹出窗口中打开“添加城市”页面(如果您不介意的话)。保存后可以执行以下操作:
Response.Write("<script>opener.RefreshDropDown('" + id  + "','" + val + "');</script>");
Response.Write("<script>window.close();</script>"); 

并添加一些像这样的JavaScript

function RefreshDropDown(val,txt)
    {
        var opt = document.createElement("option");            
        var sCtrl = document.getElementById('<%= ddlCity.ClientID %>').options.add(opt);
        opt.text = txt;
        opt.value = val;
}

这个想法源自在asp.net c#中从弹窗刷新父级下拉列表


我认为这应该被接受为答案,因为Topic Started不需要安装像SignalR这样的额外扩展。这使得任务简单而纯粹。用户不应该移动到另一个选项卡来添加新城市 - 这是一个糟糕的可用性示例,并且Topic Started通过以这种方式实现它使他自己的生活和开发更加困难。 - insomnium_
这对我来说似乎是正确的解决方法,但是需要更好地解释这个答案和相关的SO问题。这里的建议似乎是将一个aspx页面加载到弹出窗口中的iframe中,是这样吗? - Brett Caswell
您是否也建议在加载事件期间将事件侦听器附加/添加到父页面域中的帧页上的按钮,或者您是说aspx页面应在其回发期间执行response.write(隐式调用那些父级方法)? - Brett Caswell
此外,当介绍像 window.opener 这样不常见的对象时,我更喜欢更加明确地表达。https://developer.mozilla.org/en-US/docs/Web/API/Window.opener 没有必要使用简写。我会做类似于这样的事情(或多或少)- <script>var parentCallBackFunc = window.opener["RefreshDropDown"] ? window.opener.RefreshDropDown : function (args) {}; parentCallbackFunc({ "id": id, "text" : txt, "value" : val }); - Brett Caswell
如果弹出窗口阻止程序不是问题,将逻辑移入弹出页面是一个可行的选择。然而,在这里解释的所有解决方案中,如果启用了 Asp.Net 的事件验证,则下拉页可以检测到一些额外的参数(更改的下拉项)不是源自服务器的。虽然有一些方法可以从 JavaScript 触发更新面板的服务器端刷新来消除该问题。另一种选择是使用 HTML 下拉菜单而不是 ASP 下拉菜单,或者禁用事件验证(不建议)。 - boosts

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接