简体   繁体   English

如何从 CodeBehind 访问 aspx 页面中的控件

[英]How to access Controls in aspx page from CodeBehind

my aim is the following:我的目标如下:

  1. Put some ImageButtons on an aspx page (with masterpage)将一些 ImageButtons 放在 aspx 页面上(带有母版页)
  2. Each ImageButton is actually a PlaceHolder, where I want to load an Image.每个 ImageButton 实际上是一个 PlaceHolder,我想在其中加载一个 Image。 I assume to have, at start, no ImageButton.ImageUrl.我假设一开始没有 ImageButton.ImageUrl。
  3. When clicking on an ImageButton, I want the ImageButton to display an image (the final goal is to load it from local machine, but, for now I use a fixed image)单击 ImageButton 时,我希望 ImageButton 显示图像(最终目标是从本地计算机加载它,但是,现在我使用固定图像)

My idea is to change the ImageButton.imageUrl after a ImageButtonClick.我的想法是在 ImageButtonClick 之后更改 ImageButton.imageUrl。

The Aspx page has an Asp:Panel with ID=FOGLIO, and contains an ImageButton with ID=HEADERLOGO. Aspx 页面有一个 ID=FOGLIO 的 Asp:Panel,并包含一个 ID=HEADERLOGO 的 ImageButton。

I tried to google all related topics, but my code, actually refuses to work.我试图用谷歌搜索所有相关主题,但我的代码实际上拒绝工作。 Some basic mistake may be, because none of the controls in the page is retrieved, as evidenced by a Response.Write that I have put during a PostBack.一些基本错误可能是,因为没有检索到页面中的任何控件,正如我在 PostBack 期间放置的 Response.Write 所证明的那样。 I don't see anyway to do what I want.反正我看不到做我想做的事。 Does anybody have any hint?有人有任何提示吗?

Thanks in advance.提前致谢。

Aspx markup and code behind follow. Aspx 标记和后面的代码如下。

    <%@ Page Title="" Language="C#" MasterPageFile="Site.Master" AutoEventWireup="true" 
        CodeBehind="Images.aspx.cs" Inherits="Monitas.Images" %>
          <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
            <style media="all">

             .Sheet {position: relative; left: 15%; top:15%; background: white; width: 800px; 
                        height: 900px; border:3px solid #000;}

             .HeaderLogo {position: relative; background: yellow; width:240px; height:100px; 
                        left: 500px; top: 1px;  border:1px solid #000;}

           </style>

         </asp:Content>

       <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

      <asp:Panel ID="FOGLIO" class="Sheet" runat="server">

          <asp:ImageButton class="HeaderLogo" ID="HEADERLOGO" alternateText="Header Logo" 
                  runat="server" ImageAlign="Middle" OnClick="OnImageHeaderClick" />

      </asp:Panel>

     </asp:Content>

The code behind:后面的代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using static Monitas.GlobalVars;

    namespace Monitas
    {
      public partial class Images : System.Web.UI.Page
     {
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack) // in a PostBack, following the OnImageHeaderClick
        {
            Panel p = (Panel)FindControl("FOGLIO");
            Response.Write("<<" + p + ">>"); // <<<< always null
            if (p!=null)
            {
                ImageButton img = (ImageButton)FindControl("HEADERLOGO");
                Response.Write("<<" + img + ">>");
                if (img!=null)
                    img.ImageUrl=HeadImage;
            }
        }

    }

    protected void OnImageHeaderClick(object sender, ImageClickEventArgs e)
    {
        HeadImage = Server.MapPath("../Monitas/Images/FooterLogo.png"); // use another image 
                after clicking on the previous
    }


    }
  }

Barring compiler errors, all controls with runat="server" and an ID attribute, and which aren't nested within a data-bound control, will be available as fields in the code-behind.除非编译器错误,所有具有runat="server"ID属性的控件,以及未嵌套在数据绑定控件中的控件,都将作为代码隐藏中的字段提供。

In this case, you should be able to reference HEADERLOGO directly from your code-behind, without having to resort to FindControl .在这种情况下,您应该能够直接从您的代码隐藏中引用HEADERLOGO ,而不必求助于FindControl

If all else fails, the sender parameter of the OnImageHeaderClick event handler will also be a reference to the image button.如果所有其他方法都失败,则OnImageHeaderClick事件处理程序的sender参数也将是对图像按钮的引用。

It's also worth pointing out that you change the HeadImage property after setting the ImageUrl property.还值得指出的是,您在设置ImageUrl属性更改了HeadImage属性。 The update will not be visible until you click on the image button a second time.在您再次单击图像按钮之前,更新将不可见。

And finally, Server.MapPath will return the physical path of the file on your server.最后, Server.MapPath将返回文件在服务器上的物理路径。 That won't work as an image URL: the user browsing your site almost certainly won't have an image file in the same path on their computer;这不能作为图像 URL:浏览您网站的用户几乎肯定不会在他们的计算机上的相同路径中拥有图像文件; and even if they did, it's almost certainly not the same image as the one on your server;即使他们这样做了,也几乎可以肯定它与您服务器上的图像不同; and even if it was, a website cannot reference images stored on the local filesystem.即使是这样,网站也无法引用存储在本地文件系统上的图像。

protected void OnImageHeaderClick(object sender, ImageClickEventArgs e)
{
    HeadImage = "~/Monitas/Images/FooterLogo.png";
    
    // If you want the image URL to be updated immediately:
    HEADERLOGO.ImageUrl = HeadImage;
}

Yes, it probably better to use a listview (my favorte), but say lets use a grid view.是的,使用列表视图(我最喜欢的)可能更好,但是说让我们使用网格视图。

We have this grid view with some columns, and a image button:我们有这个带有一些列的网格视图和一个图像按钮:

eg this:例如这个:

    <div style="padding:30px;width:50%">

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                DataKeyNames="ID" CssClass="table" >
                <Columns>
                    <asp:BoundField DataField="Fighter" HeaderText="Fighter"  />
                    <asp:BoundField DataField="Engine" HeaderText="Engine"  />
                    <asp:BoundField DataField="Thrust" HeaderText="Thrust"  />
                    <asp:BoundField DataField="Description" HeaderText="Description" />

                    <asp:TemplateField HeaderText="View">
                        <ItemTemplate>
                        <asp:ImageButton ID="btnImage" runat="server" Height="68px" Width="149px"
                            OnClientClick ="popimage(this);return false"
                            ImageUrl = '<%# Eval("ImagePath") %>' /> 
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
    </div>

Now our data is this:现在我们的数据是这样的:

在此处输入图像描述

And code to load is this:要加载的代码是这样的:

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

    void LoadGrid()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters", conn))
            {
                conn.Open();
                DataTable rstData = new DataTable();
                rstData.Load(cmdSQL.ExecuteReader());
                GridView1.DataSource = rstData;
                GridView1.DataBind();
            }
        }
    }

And now we have this:现在我们有了这个:

在此处输入图像描述

Now, I have jQuery, but we COULD add some code to click on a image, and dispay it say in a popup - much larger.现在,我有 jQuery,但我们可以添加一些代码来单击图像,并在弹出窗口中显示它 - 更大。

So on the image button, we have a click event.所以在图片按钮上,我们有一个点击事件。 We stuff the given row click (url) in to a MUCH larger image control we have hidden on the page, and then call jQuery.UI "dialog' to display that image in a dialog.我们将给定的行点击(url)填充到我们隐藏在页面上的更大的图像控件中,然后调用 jQuery.UI“对话框”以在对话框中显示该图像。

So, lets add the click event - and WE CAN do this 100% client side!!所以,让我们添加点击事件 - 我们可以做到 100% 客户端!

So, we add a div to hold the image, and this code:所以,我们添加一个 div 来保存图像,这段代码:

                <div id="imagepop" style="display:none;text-align:center;height:80%">
                    <asp:Image ID="Image1" runat="server" ClientIDMode="Static"
                    style="height:96%"/>
                </div>

            <script>
                function popimage(btn) {
                    FromImage = $(btn)
                    ToImage = $("#Image1")
                    ToImage.attr("src", FromImage.attr("src"))

                    pHeight = ($(window).height() * 0.96)
                    pWidth = ($(window).width() * 0.80)

                    myDialog = $("#imagepop");                    
                    myDialog.dialog({
                        title: "Fighter",
                        modal: true,
                        height: pHeight,
                        width: pWidth,
                        closeText: "",
                        show : "fade",
                        buttons: {

                            Ok: function () {
                                myDialog.dialog("close")
                            }
                        }
                    })
                }
            </script>

So, now I click on the image in the row, and we have this:所以,现在我单击该行中的图像,我们有这个:

在此处输入图像描述

So, use a grid or listview - even a repeater.因此,使用网格或列表视图 - 甚至是中继器。 Place one image control, and repeat it for the many pictures you want to display.放置一个图像控件,然后对要显示的许多图片重复此操作。

Fyi: I assume both jquery and jquery.ui for the dialog pop up.仅供参考:我假设 jquery 和 jquery.ui 都会弹出对话框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM