【问题标题】:Change Image URL Dynamically in .ascx page from .aspx page从 .aspx 页面动态更改 .ascx 页面中的图像 URL
【发布时间】:2012-11-23 07:48:42
【问题描述】:

我有用户控件页面 (.ascx),其中包含网站的标题图像。我需要在 webform(.aspx) 中动态更改 Header 图片。

我的 .aspx 代码:

protected void Page_PreInit(object sender, EventArgs e)
{
   Control hdrCtl = null;
   try
   {                               
       hdrCtl = LoadControl("~/UI/Header.ascx");
       if (hdrCtl != null)
       {    
           Image src = (Image)hdrCtl.FindControl("imgHeader");                                     
           src.ImageUrl = "~/Content/assets/images/editorial_1.jpg";
       }
   }
   catch (Exception ex)
   {
       Trace.Write(ex.Message);
   }
}

但图像没有改变...谁能帮我找出问题所在..

提前致谢

维杰

【问题讨论】:

  • 在你改变图像的那一行打一个断点,看看是否到达?
  • 嗨,kaf,我做到了。它在调试时显示更新的 ImagePath,但未显示在网页中。我检查了图像路径都很好,但不知道为什么更新的图像没有显示。 .

标签: asp.net image user-controls


【解决方案1】:

您的问题是您再次加载控件并且没有在页面中添加它:

hdrCtl = LoadControl("~/UI/Header.ascx");

为了使代码按原样工作,它缺少Page.Controls.Add(hdrCtl),但我认为这不是你制作它的方式。

我了解您的控件已全部存在于您的页面中,因此这不是更改图像的方法。
要更改您已准备好添加到页面上的自定义控件上的图像,您必须为自定义控件内的图像创建一个参数,如下所示:

public string cHeaderImage
{
  set { imgHeader.ImageUrl = value; }
}

然后你就简单了

protected void Page_PreInit(object sender, EventArgs e)
{
  // this is the id of your custom control
  headerCntrID.cHeaderImage = "~/Content/assets/images/editorial_1.jpg";
}

【讨论】:

  • 嗨 Aristos 它不起作用我已经完成了一个属性,正如您在调试时解释的那样,它显示更新后的 Imagepath,但它没有显示图像,并且在 firebug 中 imageurl 属性没有更新......跨度>
  • @VijayMathew 也许需要将其移至 PageLoad 或 PageInit。您还可以调试它以查看在页面循环结束时图像是否已更改为该图像,并且您没有在代码的其他地方更改它。稍微尝试一下这个想法,它就会奏效。
猜你喜欢
  • 2013-09-08
  • 1970-01-01
  • 2014-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多