2017-09-23 19 views
0

C#에 대한 경험이 조금 있지만 ASP 측에 익숙하지 않으며 설문 조사 프로젝트를 진행하고 있습니다. MSSQL 서버에서 질문/답변을 얻고 질문에 필요한 답변 유형 (확인란, 라디오, 드롭 다운 메뉴, 텍스트 입력)에 대한 적절한 컨트롤을로드하고 해당 질문에 대한 가능한 대답을 ListItem으로 추가 한 다음 채워진 컨트롤러를 추가합니다 단일 설문 질문 웹 페이지에있는 자리 표시 자에게 응답 제출시, 자리 표시자는 다음 질문으로 다시 채워지고 응답 유형에 적절한 컨트롤러를로드합니다.C#/ASP.NET의 동적으로 생성 된 컨트롤에서 선택한 확인란/라디오 및 텍스트 입력 받기

현재 어떤 체크 박스/라디오/텍스트 입력에 대한 참조를 얻을 수 없어 제출 버튼을 클릭 할 때 사용자 응답이 무엇이든 가져 오는 데 많은 어려움을 겪고 있습니다. 선택 여부.

각 줄을 디버깅하고 스테핑하면서 로컬 변수를보고 변경되는 동안 this seems to be the hierarchy of the inserted answers at the time they are all added to the placeholder을 확인합니다.

나는 모든 항목을 검사하기 위해 submitButton (다른 것들 중에서도 아래 코드 예제에서 남음) 메소드 내 forEach 루프를 사용해 보았지만 전혀 액세스하지 못했습니다. 다양한 테스트를 한 후 대답은 두 번째로 submitButton이 눌려져서 submitButton 메서드가 실행되기 전에 무효화 된 것처럼 보입니다. 그렇다면 사용자가 제출 한 답변을 어떻게 얻을 수 있습니까?

Question.aspx.cs

protected void Page_Load(object sender, EventArgs e) 
    { 


     .... 



       else if (questionType == 2) //checkbox 
       { 
        CheckBoxQuestionController checkBoxController = (CheckBoxQuestionController)LoadControl("~/CheckBoxQuestionController.ascx"); 

        checkBoxController.ID = "checkBoxQuestionController"; 
        checkBoxController.QuestionLabel.Text = questionText; 

        SqlCommand optionCommand = new SqlCommand("SELECT * FROM answerOptionTable WHERE answerOptionTable.q_Id = " + currentQuestion, connection); 

        //run command 
        SqlDataReader optionReader = optionCommand.ExecuteReader(); 

        //loop through all results 
        while (optionReader.Read()) 
        { 
         ListItem item = new ListItem(optionReader["answerText"].ToString(), optionReader["a_Id"].ToString()); 
         int currentAnswerId = Convert.ToInt32(optionReader["a_Id"]); 

         checkBoxController.QuestionCheckBoxList.Items.Add(item); //add answer to list 
        } 

        QuestionPlaceholder.Controls.Add(checkBoxController); 

       } 


      //other questionType checking here 

      connection.Close(); 
    } 

protected void SubmitButtonClick(object sender, EventArgs e) 
    { 
     //template.Items. 
     Control resultControl = FindControl("checkBoxQuestionController"); 

     //test 1 
     CheckBoxList resultControl2 = (CheckBoxList)FindControl("checkBoxQuestionController"); 

     CheckBoxList resultControl3 = (CheckBoxList)FindControl("questionCheckBoxList"); 

     //test 123213 
     CheckBoxList Cbx = (CheckBoxList)QuestionPlaceholder.FindControl("checkBoxQuestionController"); 

     //test 2 
     //for (int i = 0; i < QuestionPlaceholder.Controls.Count; i++) 
     //{ 
     // if (QuestionPlaceholder.Controls[i].GetType() == typeof(CheckBoxList)) 
     // { 
     //  CheckBoxList myList = QuestionPlaceholder.Controls[i].GetType(); 
     // } 
     //} 

     //test 3 
     //foreach (ListItem cbList in QuestionPlaceholder.Controls.("checkBoxQuestionController") 
     //{ 
     // if (cbList.Selected) 
     // { 

     // } 
     //} 
     //test 4 
     //foreach (ListItem cb in QuestionPlaceholder.Controls.OfType<ListItem>()) 
     //{ 
     // if (cb != null) 
     // { 

     // } 
     //} 

     int count = 0; 

     List<ListItem> selected = new List<ListItem>(); 
     foreach (ListItem item in debugList.Items) 
     { 
      if (item.Selected) 
      { 
       count++; 
      } 
     } 
      Response.Redirect("Question.aspx"); 
    } 

CheckBoxQuestionController.ascx.cs

public partial class CheckBoxQuestionController : System.Web.UI.UserControl 
{ 
    //Getters and setters 
    public Label QuestionLabel 
    { 
     get 
     { 
      return questionLabel; 
     } 
     set 
     { 
      questionLabel = value; 
     } 
    } 


    public CheckBoxList QuestionCheckBoxList 
    { 
     get 
     { 
      return questionCheckBoxList; 
     } 
     set 
     { 
      questionCheckBoxList = value; 
     } 
    } 

    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 
} 

CheckBoxQuestionController.ascx 당신이 직접 checkboxlist 컨트롤을 사용하지 않는 이유

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CheckBoxQuestionController.ascx.cs" Inherits="Survey_Prototype.CheckBoxQuestionController" %> 

    <div class="bodyTitle"> 
     <asp:Label ID="questionLabel" runat="server" Text="LabelText"></asp:Label> 
    </div> 
    <div class="answerOptionContainer"> 
     <asp:CheckBoxList ID="questionCheckBoxList" runat="server"> 
     </asp:CheckBoxList> 
    </div> 

답변

0

확실하지 그러나 자신의 컨트롤을 사용하십시오.

자신 만의 컨트롤을 사용하면 직접 viewstate를 처리해야합니다. 그렇지 않으면 UC의 컨트롤 세트에 액세스 한 question.aspx.cs에서 다시 게시 후 서브 컨트롤

을 게시하면 사라집니다. 그것,하지만 페이지를 다시 게시 할 때 하위 컨트롤을 만들기 전에 viewstate가 적용되므로 실제로 사용자 선택이 손실되므로 실제로 추가 된 모든 하위 컨트롤은 사라집니다.

모든 수정 코드는 컨트롤에 넣어야합니다. 다음과 같은 재정의 된 메서드로 기본 하나를 제거하지 마십시오

다음 자식 컨트롤 (여기는 QuestionCheckBoxList)은 g ViewState가 적용되기 전에 실행되면 사용자 선택이 유지되고 옵션을 통해 어떤 방법을 사용하여 어떤 것을 볼지 선택할 수 있습니다.

 protected override void CreateChildControls() 
     { 
      base.CreateChildControls(); 
     }