簡體   English   中英

有沒有辦法使用變量來控制 VB.NET 中代碼隱藏頁面的 html 標記的 ID?

[英]Is there a way to use variables to control the ID of html tags for a code-behind page in VB.NET?

我正在制作一個簡單的表格。 我有 Default.aspx、Default.aspx.vb 和 Default.aspx.designer.vb。
Default.aspx.vb 包含一個Public jsonItems As List(Of JsonItem) ,其中JsonItem只是一個定義了一些字符串的對象,例如IdLabelType 這是由Page_Load生成的,它讀取一個 Json 文件來告訴頁面表單的內容。

然后,Default.aspx 包含:

    <ul>
      <%For Each item In jsonItems%>
      <li>
        ...
        <ol>
          <asp:TextBox ID="<%=item.Label%>" runat="server"></asp:TextBox>
        </ol>
      </li>
      <%Next%>
    </ul>

然而,這並沒有像我期望的那樣工作。 我相信這是因為設計器頁面想確切地知道頁面上的表單元素......它在設計器頁面中自動生成Protected WithEvents <%=item.label%> As ... ,並抱怨它不是t 有效名稱。

有沒有辦法做我想做的事? 我應該在.. 代碼隱藏( Default.aspx.vb )中構建整個表單,而不是我現在正在做的事情嗎?

作為記錄,我習慣於在 React 中工作,這就是我最初選擇這個方向的原因(我首先用 JS 編寫它,然后將它改編為 VB)。

將 asp.net 控件注入到頁面中往往效果不佳。

您可以注入 HTML,但話又說回來,您現在無論如何都要編寫自己的代碼,而且這並沒有太大的幫助。

作為一般方法?

我應該在.. 代碼隱藏中構建整個表單嗎

不,你不想寫那么多代碼。 您與設計器一起布置標記 - 后面的代碼是提取數據來填寫那些現有的控件。

我的意思是,您必須在某個地方定義該標記。 但是對於 web 表單,一般的想法是你放入你想要的控件。

當然,有大量的控件,而且許多控件都具有數據意識。 那么,訣竅,想法,目標?

好吧,有這么多控件選擇,通常很難選擇控件。

所以,對於像布局這樣的表格,然后是 GridView。 對於花哨的表格布局,然后是 ListView。

對於重復記錄 - 比如說“卡片視圖”,那么 datalist 效果很好。

所以在網絡表單領域? 您傾向於使用設計器來布局標記。

然后你使用后面的代碼來填寫數據,或者其他什么。

所以,假設我放入一個 Gridview,如下所示:

    <asp:GridView ID="GHotels" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="ID" CssClass="table">
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName"  />
                <asp:BoundField DataField="LastName" HeaderText="LastName"    />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName"  />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkActive" runat="server" Checked='<%# Eval("Active") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Hotel Information" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Button ID="cmdView" runat="server" Text="Info" CssClass="btn" 
                            OnClick="cmdView_Click" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

我確實使用向導來幫助我創建 GV。 (但后來我刪除了在頁面上創建的 sql 數據源)。

所以,現在我說加載網格的代碼是這樣的:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        LoadGrid
    End If
End Sub

Sub LoadGrid()

    Dim rstData As DataTable
    rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName")
    GHotels.DataSource = rstData
    GHotels.DataBind()

End Sub

Public Function MyRst(strSQL As String) As DataTable
    Dim rstData As New DataTable
    Using conn As New SqlConnection(My.Settings.TEST4)
        Using cmdSQL As New SqlCommand(strSQL, conn)
            conn.Open()
            rstData.Load(cmdSQL.ExecuteReader)
            rstData.TableName = strSQL
        End Using
    End Using
    Return rstData
End Function

我明白了:

在此處輸入圖像描述

請注意我是如何將 GV 設置為 CssClass="table" 的。 (那是引導帶類 - 所以你會得到一個漂亮的束帶)。

我有一個按鈕 - 編輯該行。

同樣,只需單擊該行的簡單按鈕即可。

因此,在網格正下方,我可以放入一個 div 和一些控件來顯示/編輯該行。

說,像這樣:

    <div id="HotelInfo" runat="server" 
        style="float:left;display: none;border:solid;padding:15px;background-color:white;width:48%"
        clientidmode="Static" >
        <style>
            .iForm label {display:inline-block;width:120px}
            .iForm input {border-radius:8px;border-width:1px;margin-bottom:10px}                
            .iForm textarea {border-radius:8px;border-width:1px;margin-bottom:10px}     
            .iForm input[type=checkbox] {margin-right:4px}
        </style>

        <div style="float:left" class="iForm">
                <label>HotelName</label><asp:TextBox ID="txtHotel" runat="server"  width="280"></asp:TextBox> <br />
                <label>First Name</label><asp:TextBox ID="txtFirst" runat="server"  width="280"></asp:TextBox> <br />
                <label>Last Name</label><asp:TextBox ID="txtLast" runat="server"  width="280"></asp:TextBox> <br />

                <label>City</label><asp:TextBox ID="tCity" runat="server"  Width="140"></asp:TextBox> <br />
                <label>Province</label><asp:TextBox ID="tProvince" runat="server"  Width="75"></asp:TextBox> <br />
        </div>
        <div style="float:left;margin-left:20px" class="iForm">
            <label>Description</label> <br />
            <asp:TextBox ID="txtNotes" runat="server" Width="450" TextMode="MultiLine" 
                Height="150px"  ></asp:TextBox> <br />
            <asp:CheckBox ID="chkActive" Text=" Active" runat="server" TextAlign="Right" />
            <asp:CheckBox ID="chkBalcony"  Text=" Has Balcony" runat="server" TextAlign="Right" />
            <asp:CheckBox ID="chkSmoking" Text="Smoking Rooms" runat="server" TextAlign="Right" />
        </div>

        <div style="clear:both">
            <asp:Button ID="cmdSave" runat="server" Text="Save" CssClass="btn" />
            <asp:Button ID="cmdCancel" runat="server" Text="Cancel" CssClass="btn"
                style="margin-left:20px" OnClientClick="$('#HotelInfo').dialog('close');return false;"
                />
            <asp:Button ID="cmdDelete" runat="server" Text="Delete" CssClass="btn"
                style="margin-left:40px"
                />
        </div>
    </div>

而且,由於我們都安裝了 jQuery,我添加了 jquery.UI。

所以在上面之后,我有這個:

    <script>
        function popinfo(pbtn, strHotelName) {

            // btn = row buttion - we use that for position of pop
            btn = $(pbtn)
            myDialog = $("#HotelInfo")
            myDialog.dialog({
                title: strHotelName,
                modal: true,
                position: { my: "left top", at: "right bottom", of: btn },
                width: "48%",
                appendTo: 'form'
            })
        }
    </script>

所以,現在我們的行點擊事件:

Protected Sub cmdView_Click(sender As Object, e As EventArgs)

    ' Row click - get hotel informaton, fill out the pop div
    Dim btn As Button = sender
    Dim gRow As GridViewRow = btn.NamingContainer

    Dim intPK As Integer = GHotels.DataKeys(gRow.RowIndex).Item("ID")
    Dim rstData As DataTable = MyRst("SELECT * FROM tblHotelsA WHERE ID = " & intPK)


    Call EditOne(rstData, btn)


End Sub

Sub EditOne(rstData As DataTable, btn As Button)

    With rstData.Rows(0)
        txtHotel.Text = .Item("HotelName").ToString
        txtFirst.Text = .Item("FirstName").ToString
        txtLast.Text = .Item("LastName").ToString
        tCity.Text = .Item("City").ToString
        tProvince.Text = .Item("Province").ToString
        chkActive.Checked = .Item("Active")
        chkBalcony.Checked = .Item("Balcony")
        chkSmoking.Checked = .Item("Smoking")
        txtNotes.Text = .Item("Description").ToString
    End With

    ' ok, div information filled out, now call our js pop function.
    Dim strHotelName = """Edit Information for " & rstData.Rows(0).Item("HotelName") & """"
    Dim strJavaScript As String = "popinfo(" & btn.ClientID & "," & strHotelName & ");"

    ViewState("rstData") = rstData
    Page.ClientScript.RegisterStartupScript(Me.GetType(), "My Pop script", strJavaScript, True)


End Sub

所以,現在我們在單擊行按鈕時看到/得到這個:

在此處輸入圖像描述

上面的保存按鈕,說這段代碼:

Protected Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click

    Dim rstData As DataTable = ViewState("rstData")

    With rstData.Rows(0)
        .Item("HotelName") = txtHotel.Text
        .Item("FirstName") = txtFirst.Text
        .Item("LastName") = txtLast.Text
        .Item("City") = tCity.Text
        .Item("Province") = tProvince.Text
        .Item("Active") = chkActive.Checked
        .Item("Balcony") = chkBalcony.Checked
        .Item("Smoking") = chkSmoking.Checked
        .Item("Description") = txtNotes.Text
    End With

    Using conn As New SqlConnection(My.Settings.TEST4)
        Using cmdSQL As New SqlCommand("SELECT * FROM tblHotelsA", conn)
            conn.Open()
            Dim da As New SqlDataAdapter(cmdSQL)
            Dim daU As New SqlCommandBuilder(da)
            da.Update(rstData)
        End Using
    End Using

    LoadGrid()

End Sub

所以,上面應該給你一些想法。

實際上,我已經厭倦了編寫相同的代碼來將一行數據發送到頁面上的控件,所以我編寫了一個簡單的例程來為我做這件事。 將數據保存回表也是如此。

因此,使用一些輔助例程,您只需拖放即可將控件添加到頁面 - 然后是一些輔助例程。

那么,我的加載代碼,並保存代碼來加載控件? 這現在是一般例程,因此我什至不再手動編寫代碼。

我采用了一個添加到控件的額外屬性。

所以,我的標記變成這樣說:

<div style="float:left" class="iForm">
 <label>HotelName</label>
 <asp:TextBox ID="txtHotel" runat="server"  width="280" f="HotelName" ></asp:TextBox> <br />
 <label>First Name</label>
 <asp:TextBox ID="txtFirst" runat="server" width="280" f="FirstName" ></asp:TextBox> <br />
    <label>Last Name</label>
    <asp:TextBox ID="txtLast" runat="server"  width="280" f="LastName"></asp:TextBox> <br />

所以,代替那些加載控件的多行代碼,我現在可以這樣做:

這個:

Sub EditOne(rstData As DataTable, btn As Button)

    With rstData.Rows(0)
        txtHotel.Text = .Item("HotelName").ToString
        txtFirst.Text = .Item("FirstName").ToString
        txtLast.Text = .Item("LastName").ToString
        tCity.Text = .Item("City").ToString
        tProvince.Text = .Item("Province").ToString
        chkActive.Checked = .Item("Active")
        chkBalcony.Checked = .Item("Balcony")
        chkSmoking.Checked = .Item("Smoking")
        txtNotes.Text = .Item("Description").ToString
    End With

    ' ok, div information filled out, now call our js pop function.
    Dim strHotelName = """Edit Information for " & rstData.Rows(0).Item("HotelName") & """"

變成:

    Call fLoader(HotelInfo, rstData.Rows(0))

所以,現在,只需一行代碼就可以加載 5 個或 25 個控件的數據。

我可以發布那個例程。

但是,總而言之?

您並沒有真正編寫代碼來創建標記。 但是,后面的代碼支持您想要對控件執行的數據操作。

那么,某種即時生成的標記? Web 表單不是這種設計方法的最佳選擇——它只是不是。

因此,生成控件和 id 相當困難,但正如您所注意到的,更糟糕​​的是,您更難以將事件添加到此類控件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM