将客户端 html 单选按钮转换为具有动态 ID 的 ASP.NET Web 控件。 (ASP.net)(VB)

发布于 2024-10-11 18:58:34 字数 3111 浏览 8 评论 0 原文

我在数据列表项模板内的 .aspx 页面中有以下客户端代码,该代码从数据库中获取问题,如下所示:

<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>

输出如下:

1) 您的年龄组是什么?
- 选项 1
- 选项 2
- 选项 3
- 选项 4

单选按钮的 ID 是动态的(“Q”和 QuestionID)。如果问题没有答案,则 GetVisible 函数将返回 false,并且隐藏包含的面板。

我一直在尝试摆脱 html 并将其替换为 asp:radiobuttons 但不可能从数据绑定中设置 id.. 只是简单地。我正在尝试类似的方法:

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

这是提供数据的函数:

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

但我发现无法使用html控件,即从代码隐藏中获取它们的.text值,或添加事件!

请专家建议一种更好的方法,用合适的 ASP.NET Web 控件或代码隐藏替换 html 并将其输出。或者为我指明正确的方向?

谢谢:0)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鹤仙姿 2024-10-18 18:58:34

我对 ASP 控件数据绑定有一些经验。您面临的问题可能是这样的事实:一旦您通过标记声明了控件,您就无法从数据绑定访问它。另外,您不应将服务器端 ID 与客户端 ID 混淆。

服务器端 ID 映射到控件的 Id 属性,用于以编程方式从代码隐藏中访问控件。客户端 ID 是将放置在标记的 id 属性中并映射到 ClientId 属性的 ID。

从你的问题来看,你需要的是构建一个多项选择调查,并且在我看来,如何生成 ID 并不重要,重要的是它们针对每个问题进行了正确的分组。

我将回答以编程方式访问数据绑定中的控件的部分,这是您问题的一部分。

这是我的代码中的一个示例。假设您有一个非常简单的 GridView,如下所示

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

它在数据绑定期间获取数据集并根据某些属性设置图像。它的工作原理与 DataList 相同,不用担心。

现在,在后面的代码中,您可以处理 RowDataBoundEvent。您无法直接访问 imgExample 对象,因为它是 ItemTemplate 的子级。绑定行后,您可以直接访问该行,然后可以使用 Control 类的 FindControl 方法

这里是 C# 代码示例(易于转换为 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";
        }
}

应用到您的案例

为了构建多项选择调查,我的建议是创建一个包含问题(外部控件)的 DataList,然后为每一行声明一个包含答案(内部控件)的 RadioButtonList。将外部数据列表与问题和答案的数据集绑定。处理 RowDataBound 事件或在 DataList 世界中调用的任何事件。当您处理该事件时,将内部单选按钮列表绑定到答案。

它应该适合你

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

╄→承喏 2024-10-18 18:58:34

我现在实际上正在做类似的事情。我正在使用 javascript 和 jQuery 动态地将控件添加到我的页面。将它们添加到我的页面后,我必须获取新控件、它们的文本等。我​​这样做的方式是这样的:

<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" />

这张表是我放置所有新控件的地方。

然后,当客户端单击“保存”按钮时,它首先调用此 javascript / jQuery 函数:

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);
    }

然后调用按钮单击的服务器端函数(这在 C# 中,适用于 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);
}

使用这样的 Control 类:

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

此代码使用 javascript 和 jQuery 获取控件,使用 JSON 序列化数据并将其保存在 asp 隐藏字段中,然后获取服务器端数据并反序列化为代码可以使用的对象。然后获取数据并执行您需要执行的操作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文