2009-08-23 2 views
0

В btnSave - обработчике событий в следующих двух строках SelectedValue всегда возвращает null.Выпадающий список asp.net, не выбирая значения

not.TargetSessionCode = this.sessionsDropDownList1.SelectedValue; 
not.CourseCode = this.coursesDropDownList1.SelectedValue; 

Может кто-нибудь сказать, почему?

Это мой ASPX код:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="TeacherComposeNotice.aspx.cs" Inherits="Ice_Web_Portal_v_3_0_WebApplication.Teacher.TeacherComposeNotice" Title="Untitled Page" %> 
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> 
    <table style="width: 270px"> 
     <tr> 
      <td style="text-align: right"> 
       Session:</td> 
      <td colspan="2"> 
       <asp:DropDownList ID="sessionsDropDownList1" runat="server" Width="178px"> 
       </asp:DropDownList></td> 
      <td colspan="1" style="width: 6px"> 
       <asp:Label ID="userNameLabel" runat="server" Text="usernameLabel" Width="167px"></asp:Label></td> 
     </tr> 
     <tr> 
      <td style="text-align: right"> 
       Courses:</td> 
      <td colspan="2"> 
       <asp:DropDownList ID="coursesDropDownList1" runat="server" Width="178px"> 
       </asp:DropDownList></td> 
       <td colspan="1"><asp:Label id="labCourses" runat="server" Width="167px" Text="labCourses"></asp:Label></td> 
     </tr> 
     <tr> 
      <td style="text-align: right"> 
       Subject:</td> 
      <td colspan="3"> 
       <asp:TextBox ID="mailSubjectTextBox" runat="server" Width="343px"></asp:TextBox></td> 
     </tr> 
     <tr> 
      <td style="text-align: right" valign="top"> 
       Content:</td> 
      <td colspan="3"> 
       <asp:TextBox ID="mailContentTextBox" runat="server" Height="181px" Width="343px" Font-Names="Verdana"></asp:TextBox></td> 
     </tr> 
     <tr> 
      <td style="text-align: right" valign="top"> 
       Expiry Date :</td> 
      <td colspan="3"> 
      </td> 
     </tr> 
     <tr> 
      <td style="text-align: right" valign="top"> 
      </td> 
      <td colspan="3" style="text-align: center"> 
       &nbsp;</td> 
     </tr> 
     <tr> 
      <td style="text-align: right" valign="top"> 
      </td> 
      <td colspan="3" style="text-align: left"> 
       <asp:Label ID="errorMessageLabel" runat="server" ForeColor="#C00000" Text="***" Width="314px"></asp:Label></td> 
     </tr> 
     <tr> 
      <td style="text-align: right" valign="top"> 
      </td> 
      <td colspan="3" style="text-align: left"> 
       <asp:Button ID="btnBack" runat="server" OnClick="btnBack_Click" Text="Back" /> 
       <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" /></td> 
     </tr> 
    </table> 
</asp:Content> 

Это мой код-за:

public partial class TeacherComposeNotice : System.Web.UI.Page 
     { 
      string username = string.Empty; 

      protected void Page_Load(object sender, EventArgs e) 
      { 
       username = (string)Request.QueryString["username"]; 

       if (!IsPostBack) 
       { 
        LoadAllSessionsToDDL(); 
        LoadAllCoursesToDDL(); 
       } 

      } 

      private void LoadAllSessionsToDDL() 
      { 
       this.sessionsDropDownList1.Items.Clear(); 

       List<Ice_Web_Portal.BO.Session_> items = Ice_Web_Portal.BO.Session_.GetAllSessions(); 

       this.sessionsDropDownList1.DataSource = items; 
       this.sessionsDropDownList1.DataTextField = "SessionName"; 
       this.sessionsDropDownList1.DataValueField = "SessionCode"; 
       this.sessionsDropDownList1.DataBind(); 

       this.sessionsDropDownList1.SelectedIndex = 0; 
      } 

      private void LoadAllCoursesToDDL() 
      { 
       this.coursesDropDownList1.Items.Clear(); 

       List<Course> items = Course.GetCourses(); 

       this.coursesDropDownList1.DataSource = items; 
       this.coursesDropDownList1.DataTextField = "CourseName"; 
       this.coursesDropDownList1.DataValueField = "CourseCode"; 
       this.coursesDropDownList1.DataBind(); 
      } 

      protected void btnBack_Click(object sender, EventArgs e) 
      { 
       Server.Transfer("~/Teacher/TeacherControlPanel.aspx?username=" + username); 
      } 

      protected void btnSave_Click(object sender, EventArgs e) 
      { 
       Ice_Web_Portal.BO.Teacher teacher = Ice_Web_Portal.BO.Teacher.GetTeacherByUsername(username); 

       if (teacher != null) 
       { 
        Notice not = new Notice(); 
        not.HangingDate = DateTime.Now; 
        not.TeacherCode = teacher.TeacherCode; 
        not.TargetSessionCode = this.sessionsDropDownList1.SelectedValue; 
        not.CourseCode = this.coursesDropDownList1.SelectedValue; 
        not.NoticeSubject = this.mailSubjectTextBox.Text; 
        not.NoticeContent = this.mailContentTextBox.Text; 
        not.ExpiryDate = DateTime.Now.AddMonths(1); 
        not.IsExpired = false; 

        bool success = Notice.Save(not); 

        if (success) 
        { 
         errorMessageLabel.Text = "Saved"; 
        } 
        else 
        { 
         errorMessageLabel.Text = "Save failed"; 
        } 
       } 
       else 
       { 
        //labErrorMessage.Text = "No teacher found"; 
       } 
      } 
     } 

ответ

1

Очень странно. Ваш код выглядит отлично. Я попытался восстановить вашу страницу со следующим кодом:

public partial class DropdownTests : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      LoadAllCoursesToDDL(); 
     } 
    } 

    private List<Course> GetDummyCourses() 
    { 
     return new List<Course>{ 
      new Course{ CourseCode = "A12", CourseName = "Introduction to Programming"}, 
      new Course{ CourseCode = "B112", CourseName = "Theory of Computing"} 
     }; 
    } 

    private void LoadAllCoursesToDDL() 
    { 
     this.coursesDropDownList1.Items.Clear(); 

     List<Course> items = GetDummyCourses(); 

     this.coursesDropDownList1.DataSource = items; 
     this.coursesDropDownList1.DataTextField = "CourseName"; 
     this.coursesDropDownList1.DataValueField = "CourseCode"; 
     this.coursesDropDownList1.DataBind(); 
    } 

    protected void btnBack_Click(object sender, EventArgs e) 
    { 
     //Server.Transfer("~/Teacher/TeacherControlPanel.aspx?username=" + username); 
    } 

    protected void btnSave_Click(object sender, EventArgs e) 
    { 
     string code = coursesDropDownList1.SelectedItem.Value; 
     string code2 = coursesDropDownList1.SelectedValue; 
    } 
} 

public class Course 
{ 
    public string CourseCode { get; set; } 
    public string CourseName { get; set; } 
} 

Это просто сработало отлично. В случае, попробуйте использовать coursesDropdownList1.SelectedItem.Value вместо «SelectedValue». Не важно, но просто попробовать.

Как попытка, я бы также создал новую страницу, скопировав там код aspx и создав для нее код. На мой взгляд, должно быть что-то еще, что заставляет его потерпеть неудачу. Вы создаете и добавляете некоторые поля в пользовательский интерфейс динамически во время выполнения? Некоторые настраиваемые серверные элементы управления и т. Д. Ваша проблема может заключаться в том, что вы потеряете ViewState.

+0

Нет. Я ничего не добавляю динамически. Что еще нужно проверить? КонечноDropDownLoat.SelectedItem имеет значение null. – anonymous

+0

Вы пытались «перепрограммировать» эту страницу. В основном размещение кода ASPX + codebehind в новом файле. Часто это помогает вам. Кстати, мой упрощенный пример работает для вас? – Juri

+1

Еще одна вещь приходит мне на ум. Проверьте, на вашей главной странице или где-то вы указали «EnableViewState = false» – Juri

1

У меня была та же проблема, но enableViewState = true - единственное решение, которое заставляет его работать. Очень странно.

Смежные вопросы