我怎么能收集在提交按钮中选择的所有单选按钮?

时间:2015-01-22 08:07:08

标签: asp.net

这是我的代码:

public partial class Play : System.Web.UI.UserControl
{

    int surveyId = 153;
    protected void Page_Load(object sender, EventArgs e)
    {
       // surveyId = int.Parse(Request[SurveyContext.SurveyID]);
        FillQuestion();

    }
    void FillQuestion()
    {
        IList<Eskadenia.Framework.Survey.Entitis.Question> QuestionLst = Eskadenia.Framework.Survey.Data.QuestionManager.GetQuestionBySurveyId(surveyId);
        try
        {
            RepPlay.DataSource = QuestionLst;
            RepPlay.DataBind();
        }
        catch (Exception ex)
        {
            Response.Write(ex.InnerException);
        }
    }

    protected void RepPlay_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        RadioButtonList rblAnswers = ((RadioButtonList)e.Item.FindControl("rblAnswers"));

        IList<Eskadenia.Framework.Survey.Entitis.Answer> answerlst;
        answerlst = Eskadenia.Framework.Survey.Data.AnswerManager.GetAnswerByQuestionID(((Eskadenia.Framework.Survey.Entitis.Question)(e.Item.DataItem)).ID);

        for (int i = 0; i < answerlst.Count; i++)
        {
            rblAnswers.Items.Add(new ListItem(answerlst[i].Name, answerlst[i].ID.ToString()));
        }

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        Response.Redirect("~/Surveys.aspx");
    }

}

1 个答案:

答案 0 :(得分:1)

首先:您应该仅对转发器进行数据绑定if(!IsPostBack)

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
       FillQuestion();
}

否则所有更改都将丢失,并且不会触发事件。

根据核心问题如何在转发器中获取所有选定的ListItem,这有用:

var allSelectedItems = RepPlay.Items.Cast<RepeaterItem>()
    .Select(ri => new{ 
         ItemIndex = ri.ItemIndex,
         SelectedItem = ((RadioButtonList) ri.FindControl("rblAnswers"))
            .Items.Cast<ListItem>()
            .First(li => li.Selected)
    });

这假设您希望ItemIndex作为标识符,如果您需要ID,您必须告诉我们它存储在何处。您也可以使用ri.FindControl("HiddenIDControl")来获取它。

由于您已注释想要字典,因此可以使用此查询:

 Dictionary<int, string> questionAnswers = RepPlay.Items.Cast<RepeaterItem>()
.ToDictionary(ri => ri.ItemIndex, ri => ((RadioButtonList)ri.FindControl("rblAnswers"))
        .Items.Cast<ListItem>()
        .First(li => li.Selected).Value);

没有LINQ,这是相同的,你是对的,在这种情况下,循环更简单:

Dictionary<int, string> questionAnswers = new Dictionary<int, string>();
foreach (RepeaterItem item in RepPlay.Items)
{ 
    string selectedValue = ((RadioButtonList)item.FindControl("rblAnswers")).SelectedValue;
    questionAnswers.Add(item.ItemIndex, selectedValue);
}

我注意到我的LINQ方法过于复杂,你总是可以使用RadioButtonList.SelectedValue,因为RadioButtonList不支持多选。