问题
EDIT 3 : FIXED !
I finally found what the problem was. Every controls where in an asp:Table, and I had to EnableViewState="true" on this table in order to be able to keep the value after postback.
Thanks everyone for the answers !
First of all, excuse me if my english is not perfect but I'll try to be the most precise as possible. I'm fighting with my problem since yesterday and have been searching all over the web for an answer..
I have a form which is made to "Create a new profile". In this form I have some DropDownLists and TextBoxes, my problem is about DropDownLists.
4 DropDown are on my page.
Let's focus on the 2 last DropDown :
The first DropDown dynamically populate the second one in function of its value.
see this picture: http://image.noelshack.com/fichiers/2013/22/1369819471-picture-help.png
1st ddl:
<asp:DropDownList ID="ddlTypePN" runat="server" DataSourceID="SqlTypePN" EnableViewState="true"
DataTextField="libelle" DataValueField="valeur" AutoPostBack="true" OnSelectedIndexChanged="ddlTypePN_SelectedIndexChanged"
OnDataBound="ddlTypePN_DataBound" > </asp:DropDownList>
2nd ddl:
<asp:DropDownList runat="server" ID="ddlFctPN" AppendDataBoundItems="false" OnDataBound="ddlFctPN_DataBound" > </asp:DropDownList>
Populate method :
void populateDdl()
{
string val = "fct"+ddlTypePN.SelectedValue.ToString().Trim(); // Used for SELECT
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["My_DB"].ConnectionString);
ddlFctPN.Items.Clear();
DataTable subjects = new DataTable();
try
{
SqlDataAdapter adapter = new SqlDataAdapter("My SELECT", sqlConn);
adapter.Fill(subjects);
ddlFctPN.DataSource = subjects;
ddlFctPN.DataTextField = "libelle";
ddlFctPN.DataValueField = "valeur";
ddlFctPN.DataBind();
}
catch (Exception ex)
{
lblErr.Text = ex.Message;
}
ddlFctPN.Items.Insert(0, new ListItem("Sélectionnez...", "null"));
}
When I Select an item in my 2nd ddl and that a PostBack occurs (even if it comes from others dropdownlists i mentionned before), the SelectedValue becomes the first value. ("Selectionnez...")
It seems like my 2nd DropDown is bounded on every postback even if it's not because of SelectedIndexChanged of my 1st DropDown.. The SelectedIndexChanged the 1st DropDown is always called on postback and so it throws "populateDdl()" at every PostBack (if a value is selected).
When I click on submit button, it register a blank value in my database.
What am I missing?
EDIT1 :
Here is PageLoad :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlTypeProf.DataBind(); // don't care
ddlSsoSrc.DataBind(); // don't care
ddlTypePN.DataBind(); // The ddl that populate my 2nd ddl
}
}
and here is 1st ddl SelectedIndexChanged :
protected void ddlTypePN_SelectedIndexChanged(object sender, EventArgs e)
{
string type = ddlTypePN.SelectedValue.ToString().Trim();
// if PNT
if (type.ToUpper().Trim().Equals("PNT"))
{
ddlFctPN.Enabled = true;
ddlTypeAv.Enabled = true;
rfvTypeAv.Enabled = true;
populateDdl();
}
else if (type.ToUpper().Trim().Equals("PNC"))
{
ddlFctPN.Enabled = true;
ddlTypeAv.Enabled = false;
rfvTypeAv.Enabled = false;
populateDdl();
}
}
EDIT 2 :
See the following picture :
http://image.noelshack.com/fichiers/2013/22/1369830738-help2.png
You can see that my 2nd ddl ("Fonction") is correctly filled BUT when I click on the submit button : the value becomes the null value ("Sélectionnez...") and so my RequiredFieldValidator makes the page not valid!
回答1:
if(!IsPostBack)
{
populateDdl();
}
回答2:
you are population DD1 in every post back
to avoid this use
if(!IsPostBack)
{
populateDdl();
}
回答3:
put this code under this condition
if(!Page.IsPostBack)
{
// Your Code Here
}
回答4:
U can use CascadingDropDown like:
<ajaxToolkit:CascadingDropDown ID="CDD1" runat="server"
TargetControlID="DropDownList2"
Category="Model"
PromptText="Please select a model"
LoadingText="[Loading models...]"
ServicePath="CarsService.asmx"
ServiceMethod="GetDropDownContents"
ParentControlID="DropDownList1"
SelectedValue="SomeValue" />
回答5:
From your mark up you haven't set the AutoPostBack property on the second drop down. So it shouldn't fire a post back when the second drop down index has changed (unless you are programmatically causing a post back).
I've copied your code into my solution, it seems to be behaving...
<asp:Label ID="lblErr" runat="server"></asp:Label>
<asp:DropDownList ID="ddlTypePN" runat="server" EnableViewState="true"
AutoPostBack="true" OnSelectedIndexChanged="ddlTypePN_SelectedIndexChanged"
OnDataBound="ddlTypePN_DataBound">
</asp:DropDownList>
<asp:DropDownList runat="server" ID="ddlFctPN" AppendDataBoundItems="false" OnDataBound="ddlFctPN_DataBound">
</asp:DropDownList>
And the code...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListItemCollection items = new ListItemCollection();
items.Add(new ListItem("PNT", "PNT"));
items.Add(new ListItem("PNC", "PNC"));
ddlTypePN.DataSource = items;
ddlFctPN.DataBind();
ddlTypePN.DataBind(); // The ddl that populate my 2nd ddl
ddlTypePN.Items.Insert(0, new ListItem("Sélectionnez...", "null"));
}
}
protected void ddlTypePN_SelectedIndexChanged(object sender, EventArgs e)
{
string type = ddlTypePN.SelectedValue.ToString().Trim();
// if PNT
if (type.ToUpper().Trim().Equals("PNT"))
{
ddlFctPN.Enabled = true;
populateDdl();
}
else if (type.ToUpper().Trim().Equals("PNC"))
{
ddlFctPN.Enabled = true;
populateDdl();
}
}
protected void ddlTypePN_DataBound(object sender, EventArgs e)
{
}
protected void ddlFctPN_DataBound(object sender, EventArgs e)
{
}
void populateDdl()
{
ddlFctPN.Items.Clear();
lblErr.Visible = false;
try
{
ListItemCollection items = new ListItemCollection();
items.Add(new ListItem("One", "1"));
items.Add(new ListItem("Two", "2"));
items.Add(new ListItem("Three", "3"));
ddlFctPN.DataSource = items;
ddlFctPN.DataBind();
}
catch (Exception ex)
{
lblErr.Text = ex.Message;
lblErr.Visible = true;
}
ddlFctPN.Items.Insert(0, new ListItem("Sélectionnez...", "null"));
}
}
回答6:
After many hours of trying to figure out a similar problem and why my dropdown wouldn't change, I checked my data and while the DataTextField info was different, the DataTextValues were the same and it was just pulling the first one each time. Check your data and see if they have different values.
回答7:
ok solucion
<script type="text/javascript">
function MtCambioRegion() {
// con JQUERY
//var regionId = $('#<%= ddlregion.ClientID %>').val();
// sin JQUERY
var regionId = document.getElementById('ContentBody_ddlRegion').value;
// var regionId = document.getElementById('ContentBody_CtrContenedoAjax_ddlRegion').value
// alert('metodo region : ' + regionId );
GetCitiesOfRegion(regionId);
}
function GetCitiesOfRegion(regionId) {
// alert('Funcion ' + regionId );
var actionData = "{'regionId': '" + regionId + "'}";
$.ajax({
type: "POST",
url: "WebTespRegionComuna.aspx/GetProComunas",
data: actionData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var ddlComuna = $("[id*=ddlComuna]");
ddlComuna.empty().append('');
$.each(r.d, function () {
ddlComuna.append($("<option></option>").val(this['id']).html(this['nombre']));
});
}
});
}
function FnSelComuna() {
var x = document.getElementById("ContentBody_ddlComuna").value;
// alert(x);
document.getElementById('ContentBody_txtComunaHiden').value = x;
}
// formulario aspx
Public Class WebTespRegionComuna
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'ControlSystema.GetSearhRegionList(ddlRegion)
Dim _ControlSystema As New ControlSystema
With _ControlSystema
.MtRegionList(ddlRegion)
End With
_ControlSystema = Nothing
End If
End Sub
<System.Web.Services.WebMethod()> _
Public Shared Function GetProComunas(regionId As String) As List(Of ComunaList)
Dim _ControlSystema As New ControlSystema
Dim _lista As List(Of ComunaList)
With _ControlSystema
_lista = .GetSearchComunaList(regionId)
End With
_ControlSystema = Nothing
Return _lista
End Function
Private Sub btnGuardarDatos_Click(sender As Object, e As System.EventArgs) Handles btnGuardarDatos.Click
Try
Dim valorcomuna As String = ddlComuna.SelectedValue
valorcomuna = txtComunaHiden.Text
Dim valorregion As String = ddlRegion.SelectedValue.ToString()
Dim _valor As String = "punto de quiebre"
Catch ex As Exception
End Try
End Sub End Class
来源:https://stackoverflow.com/questions/16810626/dynamically-filled-dropdownlist-does-not-retain-value-on-postback-asp-net-c-shar