简体   繁体   English

服务器button_click中的ASP.NET dropdownlist为空,客户端已填充ddl

[英]ASP.NET dropdownlist is empty in server button_click, the ddl is populated client side

I've a form to change some address information. 我有一个表格来更改一些地址信息。 When putting some generic ZIP code in a text box a client event is fired to populate a dropdownlist with compatible cities. 当在文本框中放置一些generic ZIP code ,会触发一个客户端事件,以使用兼容的城市填充下拉列表。

The populate is correct, the problem is no matter which value I select after, because when I click on the button to save the data, that dropdownlist in server function button_click have SelectedItem to null , have aso list Items count to 0.. 填充是正确的,无论我选择哪个值都是问题,因为当我单击按钮保存数据时,服务器功能button_click中的下拉列表将SelectedItem to null ,将aso列表项目计数为0。

I've put another dropdownlist just for test, with some random cities in it, and if I set a value on it by the same jquery function I can correctly see it in the server function, so the problem seems to be with the fact that the other is populated client side.. 我放置了另一个下拉列表用于测试,其中包含一些随机城市,如果我使用相同的jquery函数在其上设置值,则可以在服务器函数中正确看到它,因此问题似乎出在以下事实:另一个是客户端。

I've seen this: Asp.Net: Restoring client-side SelectedItem of DropDownList on server-side and the set hidden field value workaround, but I was wondering if there's a more correct way to do this.. 我已经看到了: Asp.Net:在服务器端还原DropDownList的客户端SelectedItem和设置隐藏字段值的方法,但是我想知道是否有更正确的方法来执行此操作。

<table>
    <tr>
        <td>
            <label>Address</label><br />
            <asp:TextBox ID="txtAddress" CssClass="testo" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <label>Province</label><br />
            <asp:TextBox ID="txtProvince" runat="server" />
        </td>
        <td>
            <label>City</label><br />
            <asp:DropDownList ID="ddlCity" runat="server" />
        </td>
        <td>
            <label>ZIP</label><br />
            <asp:TextBox ID="txtZIP" />
        </td>
    </tr>
    <tr>
        <td>
            <!-- Just for test set ddl by jQuery -->
            <asp:DropDownList ID="ddlTest" runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            <asp:ImageButton ID="btnSave" runat="server"
                OnClick="btnSave_Click" />
        </td>
    </tr>
</table>

$(function () {

    $(document).on('keyup', 'input[id*="txtZIP"]', function () { 
        var input = $(this);
        if (input[0].selectionStart == 5) {
            $.ajax({ 
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "CleanAddress.aspx/txtZIP_TextChanged",
                data: "{ZIP:'" + input.val() + "'}",
                dataType: "json",
                success: function (response) {
                    var cities = $.parseJSON(JSON.stringify(response.d)); 
                    if (comuni.length > 0) {
                        $("[id*=txtProvince]").val(cities[0].ID_PROVINCE);
                        $("[id*='ddlCity']").empty();
                        $.each(cities, function (key, value) {
                            $("[id*='ddlCity']").append($("<option />
").val(value.ID_CITY).text(value.CITY));
                        });
                        $("[id*='ddlCity']").removeAttr('disabled');
                        $("[id*='ddlTest']").val(9); // Just for test
                        $("[id*='ddlComuneDom']").val(cities[0].ID_CITY);
                        //alert($("[id*='ddlTest']").val());
                        //alert($("[id*='ddlCity']").val());
                        }
                    }
                },
                error: function (result) {
                    alert("Errore! " + result.status + " - " + result.statusText);
                }
            });
        }
    });

[WebMethod]
    public static List<Comuni> txtZIP_TextChanged(string ZIP)
    {
        try
        {
            List<Cities> cities = new List<Cities>();
            if ((ZIP.Trim() != "") && (ZIP.Length == 5))
            {
                dcListCitiesDataContext dc = new dcListCitiesDataContext();

                if (dc.Cities.Where(c => c.ZIP.Equals(ZIP)).Count() > 0)
                {
                    string province = dc.Cities.Where(c => c.ZIP.Equals(ZIP)).First().ID_PROVINCE.ToUpper();
                    if (province != null)
                    {
                        cities = dc.Cities.Where(c => c.ZIP.Equals(ZIP)).ToList();
                        return cities;
                    }

                }
            }
            return cities;
        }
        catch (Exception ex)
        {
            Utility.WriteLog("CleanAddress - txtZIP_TextChanged " + " - " + ex.Message, TipoLog.Error);
            throw;
        }
    }

    protected void btnSave_Click(object sender, ImageClickEventArgs e)
{
    // Here I've always ddlCity empty
    string cities= "";
    if (ddlCity.SelectedItem != null)
        cities= ddlCity.SelectedItem.ToString();
    else
        cities= ddlTest.SelectedItem.ToString();
    (...)
}

In asp webforms you should never add to server side controls on the client side. 在ASP Web窗体中,您永远不应在客户端添加服务器端控件。 Because of the abstractions applied like view state, it won't work very well and can cause really fun issues. 由于像视图状态一样应用了抽象,所以它不能很好地工作,并且会引起很多有趣的问题。

If you need to populate the list the "web forms" way you would generally place the dropdownv in an update panel, and load it by doing a partial postback. 如果需要使用“ Web表单”方式填充列表,通常将dropdownv放在更新面板中,并通过部分回发来加载它。 Then you could add to the items, or do data binding on the server side to populate it. 然后,您可以添加到项目,或者在服务器端进行数据绑定以填充它。

Of you don't like this option, make it a standard select, and don't try to use the server side control. 在您当中,您不喜欢此选项,请使其成为标准选择,并且不要尝试使用服务器端控件。 When you submit your form you should still be able to get the submitted value, and it will be much cleaner. 当您提交表格时,您仍然应该能够获得所提交的价值,它将更加干净。

As I see in this: 正如我在此看到的:

Asp.Net: Restoring client-side SelectedItem of DropDownList on server-side Asp.Net:在服务器端还原DropDownList的客户端SelectedItem

<asp:HiddenField ID="hdnCity" runat="server" />

in ZIP text change and in ddl change: 在ZIP文本更改和ddl更改中:

$("[id*='hdnCity']").val($("[id*='ddlCity'] option:selected").text());

and server side: 和服务器端:

city = hdnCity.Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM