开发者

is there a way to hold the values? - lost in postback

i have two select using as a dropdownlist for country/state

everything works as i expected but when i do a postback then i开发者_开发技巧 lost the values from the above <select...> what is the best way to retain the values and can you show me with an example please?

<asp: Button ID="Button1" runat="server" 
onclick="Button1_Click" Text="PostBack" />

thanks.


If you're using ASP.NET with some jQuery, you could set the value of a hidden field in the post back. Then in the $(document).ready() you just read that value from the hidden field.

In your code behind:

protected void Button1_Click(object sender, EventArgs e)
{
  this.countryField.Value = "WhateverValueYouWantToPersist";
}

In your aspx file:

$(document).ready(function(){
  var persistedValue = <% this.countryField.ClientID %>;
  // do something...
});

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

Update:

I came up with a little better solution. I hope you only want to capture the selected values form the select lists and don't need to persist the whole country/state collection.

I would setup my aspx page as so:

<asp:DropDownList runat="server" ID="countryField" />
<asp:DropDownList runat="server" ID="stateField" />

<asp:Button runat="server" ID="button1" OnClick="button1_click" OnClientClick="return clientSideClick()" />

<asp:HiddenField runat="server" ID="hiddenCountry" />
<asp:HiddenField runat="server" ID="hiddenState" />

In my jQuery i would have a function to handle that click, which captures the selected value(s) and sets the value for the hidden fields:

function clientSideClick() {
    var state = $("#<%= this.stateField.ClientID %> :selected").val();
    $("#<%= this.hiddenState.ClientID %>").val(state);

    var country = $("#<%= this.countryField.ClientID %> :selected").val();
    $("#<%= this.hiddenCountry.ClientID %>").val(country);
}

Then in your server side button post back event, you could capture the value of the hidden states and do whatever you need to do from there:

protected void button1_click(object sender, EventArgs e)
{
    string stateValue = this.hiddenState.Value;
    string countryValue = this.hiddenCountry.Value;
}

If you did want to re-select the previously selected Country/State pair, then after your jQuery code loads the Countries and States using your ajax routines, the previously selected values will still be in that hidden field and you can use the values from there.


You've got some options:

  • You could do some kind of 'ajax post' so the whole page will not refresh.
  • You could stream the selected data back from the server.
  • You could store the selected data into a cookie.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜