Отображение динамических изображений с использованием кода .NET Cookies - PullRequest
0 голосов
/ 07 февраля 2011

Я использую jQuery и C # для отображения изображений слайдов на странице.JQuery приходит, когда все изображения загружаются из кода C #.

У меня есть три изображения на странице, которые генерируются динамически с использованием c #.

<img id="image1" title="Enjoy a refreshing shower at 43,000 feet" alt="Enjoy a refreshing shower at 43,000 feet" src="/english/images/spa.jpg" style="display: block;">

<img id="image2"  title="The comfort of your own Private Suite" alt="The comfort of your own Private Suite" src="/english/images/suites.jpg" style="display: block;">

<img id="image3"  title="Socialize, relax, and indulge" alt="Socialize, relax, and indulge" src="/english/images/lounge.jpg" style="display: block;">

Теперь я хочу написать код C #, который будет читать выше изображения и будет хранить их в куки.И в соответствии со значением файлов cookie будут отображаться изображения.

Так что, если я увидел первое изображение, то при следующем посещении страницы будет показано второе изображение и так далее.И после последнего показанного изображения, он начнет показываться первым.В основном, я хочу реализовать приведенную ниже логику.

"Each image will show in order and a cookie will maintain which image should be shown next. But the image should not change when the user logs in. Also the cookie will be cleared in case any one of the images are changed."

Пожалуйста, сообщите мне, как начать, и был бы признателен, если бы у меня был пример кода

Спасибо!

.NET-КОД для создания изображения и скрытого ввода:

protected override void CreateChildControls()
        {

            // Always start with a clean form
            Controls.Clear();

            //Declaring the List for image list
            List<string> imageList = new List<string>();

            //Declaring the Collection object to add the image list
            NameValueCollection cookiecollection = new NameValueCollection();           

            int cntShow = 0;
            //Adding DIV4 for prev and next
            Panel div4 = new Panel();
            //Adding Input Hidden to get all the values from control
            HtmlGenericControl inputHidden = new HtmlGenericControl("input");
            foreach (FeaturedPromo promo in base.FeaturedPromos)
            {
                inputHidden = new HtmlGenericControl("input");
                inputHidden.Attributes["id"] = promo.ID + "Image";
                inputHidden.Attributes["type"] = "hidden";
                inputHidden.Attributes["src"] = promo.ImageSource;
                inputHidden.Attributes["alt"] = promo.ImageAlt;
                inputHidden.Attributes["title"] = promo.ImageTitle;
                inputHidden.Attributes["href"] = promo.ImageHref;
                inputHidden.Attributes["height"] = promo.ImageHeight;
                inputHidden.Attributes["width"] = promo.ImageWidth;
                inputHidden.Attributes["header"] = promo.ImageHeader;
                inputHidden.Attributes["subheader"] = promo.ImageSubHeader;
                inputHidden.Attributes["color"] = promo.ImageColor;

                this.Controls.Add(inputHidden);

                imageList.Add(promo.ID + "Image");

                if (cntShow == 0)
                {
                    //Add specific div for Featured Promo
                    Panel div1 = new Panel();
                    div1.Attributes["id"] = promo.ID;

                    if (cntShow == 0)
                    {
                        div1.Style["display"] = "block";
                    }
                    else
                    {
                        div1.Style["display"] = "none";
                    }

                    //Adding an Image
                    HtmlGenericControl image = new HtmlGenericControl("image");      
                    image.Attributes["src"] = promo.ImageSource;
                    image.Attributes["alt"] = promo.ImageAlt;
                    image.Attributes["title"] = promo.ImageTitle;

                    div1.Controls.Add(image);

                    //Adding two HREF for navigation
                    HtmlGenericControl alinkLeft = new HtmlGenericControl("a");
                    alinkLeft.Attributes["class"] = "slideshow-control-left";
                    alinkLeft.Attributes["href"] = "javascript:void(0);";
                    alinkLeft.Style["display"] = "inline";
                    div1.Controls.Add(alinkLeft);

                    HtmlGenericControl alinkRight = new HtmlGenericControl("a");
                    alinkRight.Attributes["class"] = "slideshow-control-right";
                    alinkRight.Attributes["href"] = "javascript:void(0);";
                    alinkRight.Style["display"] = "inline";
                    div1.Controls.Add(alinkRight);

                    //Adding Second div
                    Panel div2 = new Panel();
                    div2.CssClass = "slideshow-b";
                    div1.Controls.Add(div2);

                    //Adding Third div
                    Panel div3 = new Panel();
                    div3.CssClass = "slideshow-bl";
                    div2.Controls.Add(div3);

                    //Adding the A HREF Link
                    HtmlGenericControl alink = new HtmlGenericControl("a");
                    alink.Attributes["class"] = "slideshow-link";
                    alink.Attributes["href"] = promo.ImageHref;
                    div3.Controls.Add(alink);

                    //Adding the first span                
                    HtmlGenericControl span1 = new HtmlGenericControl("span");
                    span1.Attributes["class"] = "slideshow-header";
                    span1.InnerHtml = promo.ImageHeader;
                    alink.Controls.Add(span1);

                    //Adding line break
                    alink.Controls.Add(new LiteralControl("<br/>"));

                    //Adding the second span
                    HtmlGenericControl span2 = new HtmlGenericControl("span");
                    span2.Attributes["class"] = "slideshow-subheader";
                    span2.InnerHtml = promo.ImageSubHeader;
                    alink.Controls.Add(span2);
                    this.Controls.Add(div1);

                    if (base.FeaturedPromos.Count > 1)
                    {
                        //Adding DIV4 for prev and next
                        div4 = new Panel();
                        div4.CssClass = "slideshow-br";

                        //Adding DIV5 inside DIV4
                        Panel div5 = new Panel();
                        div5.CssClass = "slideshow-br-controls";
                        div4.Controls.Add(div5);

                        //Adding the PREV A HREF Link
                        HtmlGenericControl alinkPrev = new HtmlGenericControl("a");
                        alinkPrev.Attributes["class"] = "slideshow-br-controls-left";
                        alinkPrev.Attributes["href"] = "javascript:void(0);";
                        alinkPrev.Attributes["title"] = "Prev";
                        alinkPrev.Style["display"] = "inline";
                        alinkPrev.Attributes["CurrentDivID"] = promo.ID;
                        div5.Controls.Add(alinkPrev);

                        //Adding the span for prev and next buttons
                        HtmlGenericControl span3 = new HtmlGenericControl("span");
                        span3.Attributes["class"] = "slideshow-br-control-buttons";
                        int count = 0;
                        foreach (FeaturedPromo allPromo in base.FeaturedPromos)
                        {
                            if (count == 0)
                            {
                                //Adding the All HREF Link for Prev and Next
                                HtmlGenericControl aLLlinks = new HtmlGenericControl("a");
                                aLLlinks.Attributes["class"] = "" + count + "-banner-button";
                                aLLlinks.Attributes["href"] = "javascript:void(0);";
                                aLLlinks.Attributes["title"] = allPromo.ImageTitle;
                                aLLlinks.Style["display"] = "inline";

                                //aLLlinks.Attributes["id"] = "active-banner-slide";

                                span3.Controls.Add(aLLlinks);
                                count++;
                            }
                        }

                        div5.Controls.Add(span3);

                        //Adding the NEXT A HREF Link
                        HtmlGenericControl alinkNext = new HtmlGenericControl("a");
                        alinkNext.Attributes["class"] = "slideshow-br-controls-right";
                        alinkNext.Attributes["href"] = "javascript:void(0);";
                        alinkNext.Attributes["title"] = "Next";
                        alinkNext.Style["display"] = "inline";
                        alinkNext.Attributes["CurrentDivID"] = promo.ID;
                        div5.Controls.Add(alinkNext);
                        //div2.Controls.Add(div4);
                    }
                    this.Controls.Add(div1);
                    //this.Controls.Add(div4);
                    cntShow++;
                }
            }
            this.Controls.Add(div4);

            HttpCookie cookielist = new HttpCookie("ImageListOfCookies");

            for (int i = 0; i < imageList.Count; i++)
            {
                cookiecollection.Add("Image_" + i, imageList[i]);                
            }
            cookielist.Values.Add(cookiecollection);
            HttpContext.Current.Response.Cookies.Add(cookielist);


        }

Ответы [ 2 ]

1 голос
/ 07 февраля 2011

Если вы хотите сделать это на стороне клиента с помощью jQuery, вы можете использовать плагин cookie для чтения / записи файлов cookie. Вот пример, который установит первое изображение для отображения по умолчанию, затем создаст файл cookie с 2 значениями (LastDisplayed, Size), чтобы выяснить, какое изображение будет отображаться следующим.

Используемые сценарии

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery.cookie.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>

Используемые стили

<style type="text/css">
    .hide
    {
        display: none;
    }
</style>

Используемый JavaScript (используется плагин cookie jQuery и JSON2 * JSON2 * JSON2 *).

    $(document).ready(function () {
        // Add class to hide all the images
        $('img').addClass('hide');

        // Get the cookie to figure out the last image displayed
        var cookieval = $.cookie('the_cookie');


        if (cookieval != null) {
            // Parese cookie value into object
            var obj = JSON.parse(cookieval);

            // Check if last displayed is less than the total
            if (obj.LastDisplayed < obj.Size) {
                // Increment Count
                obj.LastDisplayed++;
                // Show next image
                $('img:eq(' + obj.LastDisplayed + ')').removeClass('hide');
            } else {
                // Reset last displayed to 0
                obj.LastDisplayed = 0;
                // Show first image
                $('img:eq(0)').removeClass('hide');
            }

            // Update Cookie
            $.cookie('the_cookie', JSON.stringify(obj));
        } else {
            // Show first image
            $('img :eq(0)').removeClass('hide');
            // Create object to store last displayed and total available
            var obj = {};
            obj.LastDisplayed = 0;
            obj.Size = $('img').length - 1;

            // Create the cookie
            $.cookie('the_cookie', JSON.stringify(obj));
        }
    });

1 голос
/ 07 февраля 2011

Если вы хотите сделать это с помощью файлов cookie, то, поскольку вы сами показываете изображения в первую очередь, чтобы знать, какие изображения будут отображаться, вместо того, чтобы хранить ссылку на изображения (которая может быть довольно длинной), сделайте это:

  • Назначьте каждому изображению идентификатор, подобный 1 для spa.jpg, 2 для suites.jpg или более, если имена файлов всегда уникальны, тогда пусть имена файлов будутидентификатор.

  • Затем, когда вы показываете изображение, добавьте идентификаторы в файлы cookie, как показано ниже (я использовал | для облегчения разделения и уменьшения количества файлов cookie до одного).

.

//For example to store "spa" if spa image has been stored
 if(Response.Cookies["Shown_Images"] != null)
 {
   Response.Cookies["Shown_Images"].Value = Response.Cookies["Shown_Images"] + "|spa";
 }
else
{
   Response.Cookies["Shown_Images"].Value = "spa";
}

Затем извлечь, если было показано spa.jpg или нет

if(Response.Cookies["Shown_Images"] != null)
{
   string[] images_shown = Response.Cookies["Shown_Images"];
   if(images_shown.Contains("spa"))
   {
       //If True then do processing;
   }
   else
   {
       //False then do as required
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...