0

我正在尝试保存在我的网站上提交数据的客户 IP 地址。我已经下载了一个示例并实现了。该脚本在网页上显示 IP 地址。我可以通过后面的代码将此提交到 sql 表。现在我想在 FormView 中使用相同的脚本,我无法将它与文本框绑定,因为它显示错误“当前上下文中不存在名称 IPaddress”。请更正以下脚本以执行此操作。谢谢...

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
    string IPAdd = string.Empty;
    IPAdd = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (string.IsNullOrEmpty(IPAdd))
        IPAdd = Request.ServerVariables["REMOTE_ADDR"];
    IPaddress.Text = IPAdd;
}
</script>

</head>

<body>

<form id="form1" runat="server">

<div>
 <asp:FormView ID="FormView1" runat="server" DataKeyNames="ID" 
    DataSourceID="SqlDataSource1" EnableModelValidation="True" DefaultMode="Insert" >
            <InsertItemTemplate>
        Your IP address:
        <asp:TextBox ID="IPaddress" runat="server" Font-Bold="true" Text='<%# Bind("IPadr") %>' />
        <br />
        Submitted by:
        <asp:TextBox ID="Submittedby" runat="server" Font-Bold="true" Text='<%# Bind("sub_by") %>' />
        <br />
        <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" 
            CommandName="Insert" Text="Insert" />
        &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" 
            CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </InsertItemTemplate>
    </asp:FormView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:IPaddressConnectionString %>" 
    DeleteCommand="DELETE FROM [mytable] WHERE [ID] = @ID" 
    InsertCommand="INSERT INTO [mytable] ([IPadr], [sub_by]) VALUES (@IPadr, @sub_by)" 
    SelectCommand="SELECT * FROM [mytable]"> 
    <DeleteParameters>
        <asp:Parameter Name="ID" Type="Int32" />
    </DeleteParameters>
    <InsertParameters>
        <asp:Parameter Name="IPadr" Type="String" />
        <asp:Parameter Name="sub_by" Type="String" />
    </InsertParameters>
    <UpdateParameters>
        <asp:Parameter Name="IPadr" Type="String" />
        <asp:Parameter Name="sub_by" Type="String" />
        <asp:Parameter Name="ID" Type="Int32" />
    </UpdateParameters>
</asp:SqlDataSource>
4

1 回答 1

0

我通过使用带有 OnDataBound 事件的以下脚本来实现:

string IPaddress;


protected void FormView1_OnDataBound(object sender, System.EventArgs e)
{
    if (FormView1.CurrentMode == FormViewMode.Insert)
    {

        TextBox IPAdd = (TextBox)FormView1.FindControl("IPaddress");
        if (IPAdd != null)
        {

            IPAdd.Text = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(IPAdd.Text))

                IPAdd.Text = Request.ServerVariables["REMOTE_ADDR"];

        }

    }

}
于 2013-08-21T05:26:30.593 回答