DIV 上的随机背景图像

发布于 2024-08-07 01:04:00 字数 2648 浏览 7 评论 0 原文

我正在尝试获取随机选取的背景图像(从 4 个图像中选择)作为 asp.net 面板的背景图像。

我遇到的问题是,在调试模式下单步执行代码时,代码可以工作。一旦您在网站上运行代码而不进行调试,所有图像都是相同的。就好像随机数没有足够快地被拾取一样。

用户控件位于数据列表内。

用户控件是这样的:

<asp:Panel ID="productPanel" CssClass="ProductItem" runat="server">

<div class="title" visible="false">
    <asp:HyperLink ID="hlProduct" runat="server" />
</div>
<div class="picture">
    <asp:HyperLink ID="hlImageLink" runat="server" />
</div>
<div class="description" visible="false">
    <asp:Literal runat="server" ID="lShortDescription"></asp:Literal>
</div>
<div class="addInfo" visible="false">
    <div class="prices">
        <asp:Label ID="lblOldPrice" runat="server" CssClass="oldproductPrice" />
        <br />
        <asp:Label ID="lblPrice" runat="server" CssClass="productPrice" /></div>
    <div class="buttons">
        <asp:Button runat="server" ID="btnProductDetails" OnCommand="btnProductDetails_Click"
            Text="Details" ValidationGroup="ProductDetails" CommandArgument='<%# Eval("ProductID") %>'
            SkinID="ProductGridProductDetailButton" /><br />
        <asp:Button runat="server" ID="btnAddToCart" OnCommand="btnAddToCart_Click" Text="Add to cart"
            ValidationGroup="ProductDetails" CommandArgument='<%# Eval("ProductID") %>' SkinID="ProductGridAddToCartButton" />
    </div>
</div>

背后的代码是这样的:

protected void Page_Load(object sender, EventArgs e)
    {

            // Some code here to generate a random number between 0 & 3
            System.Random RandNum = new System.Random();
            int myInt = RandNum.Next(4);

            if (productPanel.BackImageUrl != null)
            {
                switch (myInt)
                {
                    case 0:
                        productPanel.BackImageUrl = "../App_Themes/emmaharris/images/frame1.gif";
                        break;
                    case 1:
                        productPanel.BackImageUrl = "../App_Themes/emmaharris/images/frame2.gif";
                        break;
                    case 2:
                        productPanel.BackImageUrl = "../App_Themes/emmaharris/images/frame3.gif";
                        break;
                    case 3:
                        productPanel.BackImageUrl = "../App_Themes/emmaharris/images/frame4.gif";
                        break;
                }

            }
           // End of new code to switch background images

    }

T

I'm trying to get a randomly picked background image (from a selection of 4 images) to appear as the background image for a asp.net panel.

The problem I have is that the code works when stepping through the code in debug mode. Once you run the code on the website without debugging, all the images are the same. Its almost as if the random number is not getting picked up quick enough.

The usercontrol is inside of a datalist.

The usercontrol is this:

<asp:Panel ID="productPanel" CssClass="ProductItem" runat="server">

<div class="title" visible="false">
    <asp:HyperLink ID="hlProduct" runat="server" />
</div>
<div class="picture">
    <asp:HyperLink ID="hlImageLink" runat="server" />
</div>
<div class="description" visible="false">
    <asp:Literal runat="server" ID="lShortDescription"></asp:Literal>
</div>
<div class="addInfo" visible="false">
    <div class="prices">
        <asp:Label ID="lblOldPrice" runat="server" CssClass="oldproductPrice" />
        <br />
        <asp:Label ID="lblPrice" runat="server" CssClass="productPrice" /></div>
    <div class="buttons">
        <asp:Button runat="server" ID="btnProductDetails" OnCommand="btnProductDetails_Click"
            Text="Details" ValidationGroup="ProductDetails" CommandArgument='<%# Eval("ProductID") %>'
            SkinID="ProductGridProductDetailButton" /><br />
        <asp:Button runat="server" ID="btnAddToCart" OnCommand="btnAddToCart_Click" Text="Add to cart"
            ValidationGroup="ProductDetails" CommandArgument='<%# Eval("ProductID") %>' SkinID="ProductGridAddToCartButton" />
    </div>
</div>

and the code behind is this:

protected void Page_Load(object sender, EventArgs e)
    {

            // Some code here to generate a random number between 0 & 3
            System.Random RandNum = new System.Random();
            int myInt = RandNum.Next(4);

            if (productPanel.BackImageUrl != null)
            {
                switch (myInt)
                {
                    case 0:
                        productPanel.BackImageUrl = "../App_Themes/emmaharris/images/frame1.gif";
                        break;
                    case 1:
                        productPanel.BackImageUrl = "../App_Themes/emmaharris/images/frame2.gif";
                        break;
                    case 2:
                        productPanel.BackImageUrl = "../App_Themes/emmaharris/images/frame3.gif";
                        break;
                    case 3:
                        productPanel.BackImageUrl = "../App_Themes/emmaharris/images/frame4.gif";
                        break;
                }

            }
           // End of new code to switch background images

    }

T

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

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

发布评论

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

评论(3

西瑶 2024-08-14 01:04:00

有时,随机并不是真正的随机...

Jon Skeet 有一篇关于该主题的好文章: 为什么我一次又一次地从 Random 中得到相同的数字?

直接引用 Jon 有一次告诉我的话:

伪随机数生成器(例如
System.Random)实际上并不是随机的 -
它总是会产生相同的结果
初始化时的结果序列
具有相同的数据。数据是
用于初始化的是一个数字
称为种子。

基本问题是当你
使用以下命令创建 Random 的新实例
无参数构造函数(如
我们在这里做的)它使用了一个种子
从“当前时间”开始。这
计算机对“当前时间”的概念
每 15 毫秒只能改变一次(其中
是计算中的永恒) - 所以如果
您创建了几个新实例
随机地快速连续地,他们会
都有相同的种子。

你通常想要什么(假设你
不在乎能否
重现准确的结果,而您却没有
需要加密安全的随机数
数字生成器)就是有一个
在整个程序中随机使用,
第一次使用时进行初始化。
听起来你可以使用
某处的静态场(暴露为
property) - 基本上是一个单身人士。
不幸的是 System.Random 不是
线程安全 - 如果你从两个地方调用它
不同的线程,你可以得到
问题(包括得到相同的
两个线程中的数字序列)。

这就是我创建 StaticRandom 的原因
我的小实用工具箱 - 它是
基本上是一种线程安全的获取方式
随机数,使用单个
Random 的实例和一个锁。看
http://www.yoda.arachsys.com/csharp/miscutil/用法/staticrandom.html
举个简单的例子,以及
http://pobox.com/~skeet/csharp/miscutil
对于图书馆本身。

Jon Skeet 的杂项实用随机生成器

using System;

namespace MiscUtil
{
    /// <summary>
    /// Thread-safe equivalent of System.Random, using just static methods.
    /// If all you want is a source of random numbers, this is an easy class to
    /// use. If you need to specify your own seeds (eg for reproducible sequences
    /// of numbers), use System.Random.
    /// </summary>
    public static class StaticRandom
    {
        static Random random = new Random();
        static object myLock = new object();

        /// <summary>
        /// Returns a nonnegative random number. 
        /// </summary>      
        /// <returns>A 32-bit signed integer greater than or equal to zero and less than Int32.MaxValue.</returns>
        public static int Next()
        {
            lock (myLock)
            {
                return random.Next();
            }
        }

        /// <summary>
        /// Returns a nonnegative random number less than the specified maximum. 
        /// </summary>
        /// <returns>
        /// A 32-bit signed integer greater than or equal to zero, and less than maxValue; 
        /// that is, the range of return values includes zero but not maxValue.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">maxValue is less than zero.</exception>
        public static int Next(int max)
        {
            lock (myLock)
            {
                return random.Next(max);
            }
        }

        /// <summary>
        /// Returns a random number within a specified range. 
        /// </summary>
        /// <param name="min">The inclusive lower bound of the random number returned. </param>
        /// <param name="max">
        /// The exclusive upper bound of the random number returned. 
        /// maxValue must be greater than or equal to minValue.
        /// </param>
        /// <returns>
        /// A 32-bit signed integer greater than or equal to minValue and less than maxValue;
        /// that is, the range of return values includes minValue but not maxValue.
        /// If minValue equals maxValue, minValue is returned.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">minValue is greater than maxValue.</exception>
        public static int Next(int min, int max)
        {
            lock (myLock)
            {
                return random.Next(min, max);
            }
        }

        /// <summary>
        /// Returns a random number between 0.0 and 1.0.
        /// </summary>
        /// <returns>A double-precision floating point number greater than or equal to 0.0, and less than 1.0.</returns>
        public static double NextDouble()
        {
            lock (myLock)
            {
                return random.NextDouble();
            }
        }

        /// <summary>
        /// Fills the elements of a specified array of bytes with random numbers.
        /// </summary>
        /// <param name="buffer">An array of bytes to contain random numbers.</param>
        /// <exception cref="ArgumentNullException">buffer is a null reference (Nothing in Visual Basic).</exception>
        public static void NextBytes(byte[] buffer)
        {
            lock (myLock)
            {
                random.NextBytes(buffer);
            }
        }
    }
}

Sometimes, Random isn't really Random...

Jon Skeet has a good article on the topic: Why am I getting the same numbers out of Random time and time again?

To quote directly what Jon had told me one time:

A pseudo-random number generator (like
System.Random) isn't actually random -
it will always produce the same
sequence of results when initialised
with the same data. The data that's
used for initialisation is a number
called the seed.

The basic problem is that when you
create a new instance of Random using
the parameterless constructor (as
we're doing here) it uses a seed taken
from "the current time". The
computer's idea of "the current time"
may only change once every 15ms (which
is an eternity in computing) - so if
you create several new instances of
Random in quick succession, they will
all have the same seed.

What you usually want (assuming you
don't care about being able to
reproduce exact results, and you don't
need a cryptographically secure random
number generator) is to have a single
Random used throughout your program,
initialised the first time it's used.
That sounds like you could just use a
static field somewhere (exposed as a
property) - basically a singleton.
Unfortunately System.Random isn't
thread-safe - if you call it from two
different threads, you could get
problems (including getting the same
sequence of numbers in both threads).

This is why I created StaticRandom in
my little utilities toolbox - it's
basically a thread-safe way of getting
random numbers, using a single
instance of Random and a lock. See
http://www.yoda.arachsys.com/csharp/miscutil/usage/staticrandom.html
for a quick example, and
http://pobox.com/~skeet/csharp/miscutil
for the library itself.

Jon Skeet's Misc Utility Random Generator

using System;

namespace MiscUtil
{
    /// <summary>
    /// Thread-safe equivalent of System.Random, using just static methods.
    /// If all you want is a source of random numbers, this is an easy class to
    /// use. If you need to specify your own seeds (eg for reproducible sequences
    /// of numbers), use System.Random.
    /// </summary>
    public static class StaticRandom
    {
        static Random random = new Random();
        static object myLock = new object();

        /// <summary>
        /// Returns a nonnegative random number. 
        /// </summary>      
        /// <returns>A 32-bit signed integer greater than or equal to zero and less than Int32.MaxValue.</returns>
        public static int Next()
        {
            lock (myLock)
            {
                return random.Next();
            }
        }

        /// <summary>
        /// Returns a nonnegative random number less than the specified maximum. 
        /// </summary>
        /// <returns>
        /// A 32-bit signed integer greater than or equal to zero, and less than maxValue; 
        /// that is, the range of return values includes zero but not maxValue.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">maxValue is less than zero.</exception>
        public static int Next(int max)
        {
            lock (myLock)
            {
                return random.Next(max);
            }
        }

        /// <summary>
        /// Returns a random number within a specified range. 
        /// </summary>
        /// <param name="min">The inclusive lower bound of the random number returned. </param>
        /// <param name="max">
        /// The exclusive upper bound of the random number returned. 
        /// maxValue must be greater than or equal to minValue.
        /// </param>
        /// <returns>
        /// A 32-bit signed integer greater than or equal to minValue and less than maxValue;
        /// that is, the range of return values includes minValue but not maxValue.
        /// If minValue equals maxValue, minValue is returned.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">minValue is greater than maxValue.</exception>
        public static int Next(int min, int max)
        {
            lock (myLock)
            {
                return random.Next(min, max);
            }
        }

        /// <summary>
        /// Returns a random number between 0.0 and 1.0.
        /// </summary>
        /// <returns>A double-precision floating point number greater than or equal to 0.0, and less than 1.0.</returns>
        public static double NextDouble()
        {
            lock (myLock)
            {
                return random.NextDouble();
            }
        }

        /// <summary>
        /// Fills the elements of a specified array of bytes with random numbers.
        /// </summary>
        /// <param name="buffer">An array of bytes to contain random numbers.</param>
        /// <exception cref="ArgumentNullException">buffer is a null reference (Nothing in Visual Basic).</exception>
        public static void NextBytes(byte[] buffer)
        {
            lock (myLock)
            {
                random.NextBytes(buffer);
            }
        }
    }
}
看透却不说透 2024-08-14 01:04:00

您确定您的页面没有被缓存吗?在页面上查看源代码。

哦,应该有一些像 urand 或 srand 这样的函数来使 random 更加随机。

Are you sure your page isn't cached? Do a view source on page.

Oh and there should be some function like urand or srand to make random more random.

心头的小情儿 2024-08-14 01:04:00

我想知道您是否在面板上进行了某种程度的缓存操作,这导致它无法在生产模式下通过服务器端处理运行。

I wonder if you have some level of caching operating on the panel which is causing it to not run through the server side processing in production mode.

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