开发者

Converting client side html radio buttons to asp.net web controls with dynamic ids. (ASP.net)(VB)

开发者 https://www.devze.com 2023-02-04 00:58 出处:网络
I have the following client side code in .aspx page within a datalist itemtemplate that takes questions from the database like this:

I have the following client side code in .aspx page within a datalist itemtemplate that takes questions from the database like this:

<Itemtemplate>
<b> <%=GetQuestionNum()%>)
           <%#Server.HtmlEncode(Eval("Text").ToString())%></b> 
            <br />
            <asp:Panel ID="A" runat="server" Visible='<%#GetVisible(Eval("OptionA").Tostring())%>'>
                <input name="Q<%#Eval("ID")%>" type="radio" value="A">
                <%#Server.HtmlEncode(Eval("OptionA").ToString())%>
                </option><br />
            </asp:Panel>
            <asp:Panel ID="B" runat="server" Visible='<%#GetVisible(Eval("OptionB").Tostring())%>'>
                <input name="Q<%#Eval("ID")%>" type="radio" value="B">
                <%#Server.HtmlEncode(Eval("OptionB").ToString())%>
                </option><br />
            </asp:Panel>
            <asp:Panel ID="C" runat="server" Visible='<%#GetVisible(Eval("OptionC").Tostring())%>'>
                <input name="Q<%#Eval("ID")%>" type="radio" value="C">
                <%#Server.HtmlEncode(Eval("OptionC").ToString())%>
                </option><br />
            </asp:Panel>
            <asp:Panel ID="D" runat="server" Visible='<%#GetVisible(Eval("OptionD").Tostring())%>'>
                <input name="Q<%#Eval("ID")%>" type="radio" value="D">
                <%#Server.HtmlEncode(Eval("OptionD").ToString())%>
                </option><br />
            </asp:Panel></itemtemplate>

The output is like:

1) What is your age group?

- Option 1

- Option 2

- Option 3

- Option 4

The ID's of the radio buttons are dynamic ("Q" & QuestionID). If there is no answer to a question then the GetVisible function returns false and the containing panel is hidden.

I have been trying to get rid of the html and replace these with asp:radiobuttons but it is not possible to set id's from databinding.. only simply. I was trying something like:

<asp:RadioButton ID="Q<%#Eval("ID")%>" runat="server" Visible='<%#GetVisible(Eval("OptionA").Tostring())%>'
                Text='<%#Server.HtmlEncode(Eval("OptionA").ToString())%>' />

Here is the function that provides data:

Public Shared Function GetQuestionsForSurvey(ByVal id As Integer) As DataSet
    Dim dsQuestions As DataSet = New DataSet()
    Try
        Using mConnection As New SqlConnection(Config.ConnectionString)
            Dim mCommand As SqlCommand = New SqlCommand("sprocQuestionSelectList", mConnection)
            mCommand.CommandType = CommandType.StoredProcedure
            Dim myDataAdapter As SqlDataAdapter = New SqlDataAdapter()
            myDataAdapter.SelectCommand = mCommand
            mCommand.CommandType = CommandType.StoredProcedure
            mCommand.Parameters.AddWithValue("@id", id)
            myDataAdapter.Fill(dsQuestions)
         开发者_运维问答   mConnection.Close()
            Return dsQuestions
        End Using
    Catch ex As Exception
        Throw
    End Try
End Function

but I'm finding it impossible to work with the html controls, i.e get their .text value from codebehind, or adding events!

Please can an expert suggest a better way to replace the html with suitable asp.net web controls or from the codebehind and output it. Or point me in the right direction?

Thanks :0)


I had some experience with ASP controls and data binding. The problem you are facing is probably the fact that once you declare a control via markup you can't access it from data binding. Also, you should not confuse the server-side ID with the client-side ID.

The server-side ID, mapped to Id property of controls, is used to programmatically access the control from code behind. Client-side ID is the ID that will be placed in tag's id attribute and is mapped to ClientId property.

Judging from your question, what you need is to build a multi-choice survey, and, in my opinion, it's not important how the IDs are generated, just that they are properly grouped for each question.

I'll answer the part of programmatically accessing controls in data binding, which is a part of your question.

Here is an example from my code. Suppose you have a very simple GridView like this

<asp:GridView ID="example" runat="server" OnRowDataBound="DataBound">
    <Columns>
        <asp:TemplateField HeaderText="New">
            <ItemTemplate>
                <asp:Image ID="imgExample" runat="server" />
            </ItemTemplate>
    </Columns>
</asp:GridView>

It takes a data set during data binding and sets the image according to some property. It works the same as DataList, don't worry.

Now, in code behind, you handle the RowDataBoundEvent. You can't access the imgExample object directly, because it's a child of the ItemTemplate. When the row is bound, you have direct access to the row and then you can use the FindControl method of Control class

Here is C# code example (easy to convert to VB)

protected void DataBound(object sender, GridViewRowEventArgs e)
{
        if (e.Row.RowType == DataControlRowType.DataRow) //Required
        {
            GridViewRow row = e.Row;

            [...] //get an email message

            (row.Cells[0].FindControl("imgExample") as Image).ImageUrl = (email.AlreadyRead)
                                                                            ? "Mail_Small.png"
                                                                            : "Mail_New_Small.png";
        }
}

Application to your case

In order to build a multi-choice survey, my advice is to create a DataList that will hold questions (the outer control) and then, for each row, declare a RadioButtonList that holds answers (the inner control). Bind the outer data list to the data set of questions and answers. Handle the RowDataBound event or whatever it's called in the DataList world. When you handle that event, bind the inner radiobuttonlist to the answers.

It should work for you


I am actually working on something similar at the moment. I am using javascript and jQuery to dynamically add controls to my page. After adding them to my page I have to get the new controls, their text, etc. The way I've been doing it is something like this:

<table id='BuilderTable' class="BuilderTable">
    <tbody class='BuilderBody'>
    </tbody>
</table>
<asp:Button runat="server" ID="saveButton" OnClick="SaveButton_Click" OnClientClick="SaveData()"
    Text="Save Form" />
<asp:HiddenField runat="server" ID="controlsData" />

This table is where I put all my new controls.

Then when the client clicks the save button it first calls this javascript / jQuery function:

function SaveData() {
        var controlRows = $('#BuilderTable tr.control');
        var controls= [];
        controlRows.each(function (index) {
            //process control information here ...
            controlText = //use jQuery to get text, etc...
            var control = {
                Index: (index + 1),
                Text: controlText
            };
            controls.push(control);
        });
        var str = JSON.stringify(questions);
        $('#<%= controlsData.ClientID %>').val(str);
    }

Then the server side function for the button click is called (this in in C#, adapt to VB).

protected void SaveButton_Click(object sender, EventArgs e)
{
        JavaScriptSerializer jss = new JavaScriptSerializer();
        string str = controlsData.Value;
        List<Control> controls = jss.Deserialize<List<Control>>(str);
}

Using a Control class like this:

public class Control
{
        public int Index { get; set; }
        public string Text { get; set; }
}

This code uses javascript and jQuery to get your controls, JSON to serialize the data and save it in a asp hiddenfield then grab the data server-side and deserialize into objects that your code can use. Then take the data and do whatever you need to.

0

精彩评论

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