具有可变图像大小的Ajax SlideShowExtender

时间:2017-02-16 06:49:04

标签: c# slideshow ajaxcontroltoolkit

我使用Visual Studio Community 2015在AjaxToolKit中有SlideShowExtender ASP.net C# website。所显示的图片具有不同的宽高比(因为图像高度和宽度是固定的,因此大多数都是扭曲的。我正在寻找一种显示图像而不失真的方法,并且无需手动编辑每个图像,然后再将其提供给 SlideShowExtender
例如,目标图像控制的高度和宽度属性是否可以在显示之前进行调整?
如果需要在JavaScript中完成,我需要代码帮助,因为我已经设法到目前为止只在服务器端执行所有操作,而且我知道很少的JavaScript。

根据要求添加代码

选择的文件如下。 SlideShowExtender在SlideShow.aspx中定义。 TinyNPm.Master:

<%@ Master Language="C#" AutoEventWireup="True" CodeBehind="TinyNPm.Master.cs" Inherits="TinyNP.TinyNPm" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>The TinyNP Project</title>
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
    <style>
        body {font-family:Arial; margin:0;}
        .popup {
            background-color: #ddd;
            margin: 0px auto;
            width: 330px;
            position: relative;
            border: Gray 2px inset;
        }
        .popup .content {
            padding: 20px;
            background-color: #ddd;
            float: left;
        }
        .displayUnset{display:unset}
        .displayNone {display:none}
        a:link {background-color:antiquewhite;}
        a:visited {background-color:antiquewhite;}
        a:hover {background-color:burlywood;}
        a:active {background-color:aqua;}

        li a {
            display: block;
            color: #000;
            padding: 8px 16px;
            text-decoration: none;
        }
        li a.active {
            background-color:brown;
            color: burlywood;
        }
        li a:hover:not(.active) {
            background-color:burlywood;
            color: black;
        }
        table {
            border: 0px solid grey; background-color:burlywood; height:auto; width:100%;}
        tr {background-color:wheat}
        th, td {
            border: 0px solid grey;
            border-radius: 0px;
            font-family: Arial;
            padding: 2px;
        }
        .GvGrid:hover { background-color:burlywood}

    </style>
</head>
<body runat="server"  id="Body1" style="height:100%">
    <form id="form1" runat="server" >
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
        </div>

        <div style="overflow-x:auto; height:100%">
            <asp:Table Id="Table1" style="color:sienna; height:100%" runat="server">
                <asp:TableRow >
                    <asp:TableCell ColumnSpan="3" HorizontalAlign="Right">
                        <%-- In the following CheckBox the 'Checked' attribute is coordinated with the value of NavCheckBoxChecked in Global.asax.cs --%>
                        <asp:CheckBox ID="NavCheckBox" runat="server" Checked="true"
                            Text="Nav box in left margin moves up and down when browser window height changes"
                            OnCheckedChanged="NavCheckBox_CheckedChanged"
                            AutoPostBack="true" Font-Size="X-Small" />
                    </asp:TableCell>
                </asp:TableRow>
                <asp:TableRow>
                    <asp:TableCell rowspan="3" style="vertical-align:top; width:110px">
                            <div style="text-align:center; color:sandybrown">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Site&nbsp;Navigation&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                            <ajaxToolkit:AlwaysVisibleControlExtender ID="AlwaysVisibleControlExtender1" runat="server" TargetControlID="Menu1"
                                VerticalSide="Middle" HorizontalSide="Left" Enabled="true"/>
                            <asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" Orientation="Vertical"
                                    StaticDisplayLevels="4" Font-Size="Small" BorderColor="#dd7711" BorderStyle="Outset" ItemWrap="True"
                                    OnMenuItemClick="Menu1_OnMenuItemClick" >
                                <DataBindings>
                                    <asp:MenuItemBinding DataMember="SiteMapNode" TextField="Title" />
                                </DataBindings>
                                <StaticMenuItemStyle Height="20px" VerticalPadding="0px" Font-Bold="true" ForeColor="Brown"/>
                                <StaticSelectedStyle BackColor="Yellow"/>
                                <LevelMenuItemStyles>
                                    <asp:MenuItemStyle Font-Size="Medium" />
                                    <asp:MenuItemStyle Font-Size="Small" />
                                    <asp:MenuItemStyle Font-Size="Smaller" ForeColor="#c25f1d" />
                                    <asp:MenuItemStyle Font-Size="X-Small" ForeColor="#666666" />
                                    <asp:MenuItemStyle Font-Size="X-Small" Forecolor="#808080"/>
                                </LevelMenuItemStyles>
                            </asp:Menu>
                                <br />
                                <br />
                                <div style="background-color:rgba(235, 251, 32, 0.64); color:sandybrown">Yellow highlight</div><div style="color:sandybrown"> indicates currently selected menu item</div>
                                <br />
                                <br />
                                <div style="text-align:center;  color:sandybrown">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Site&nbsp;Navigation&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                                <br />
                                <br />
                                <div style="background-color:rgba(235, 251, 32, 0.64); color:sandybrown">Yellow highlight</div><div style="color:sandybrown"> indicates currently selected menu item</div>
                                <br />
                                <br />
                                <div style="text-align:center;  color:sandybrown">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Site&nbsp;Navigation&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                                <br />
                                <br />
                                <div style="background-color:rgba(235, 251, 32, 0.64); color:sandybrown">Yellow highlight</div><div style="color:sandybrown"> indicates currently selected menu item</div>
                                <br />
                                <br />
                                <div style="text-align:center;  color:sandybrown">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Site&nbsp;Navigation&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
                    </asp:TableCell>
                    <asp:TableCell style="border-right:none" HorizontalAlign="Center" >
                        <asp:Label id="lblHeaderText" style="text-align:center; font-size:larger; font-weight:bold" runat="server" >
                            &nbsp; The TinyNP Project Common Header &nbsp;
                        </asp:Label>
                        <div style="text-align:center">
                            <asp:LoginView ID="LoginView1" runat="server" >
                                <AnonymousTemplate>
                                    You are not logged in
                                </AnonymousTemplate>
                                <LoggedInTemplate>
                                    Currently logged in user:&nbsp<asp:LoginName ID="LoginName1" runat="server" />
                                </LoggedInTemplate>
                            </asp:LoginView>
                            &nbsp;&nbsp;&#9866;&nbsp;&nbsp;
                            <asp:LoginStatus ID="LoginStatus1" runat="server" LoginText="Log in" LogoutText="Log out" Font-Size="Medium" />
                        </div>
                    </asp:TableCell>
                    <asp:TableHeaderCell style="border-left:none">
                        <asp:Image ImageUrl="~/i/GenericLogo.jpg" AlternateText="Generic Logo" height="80" width="107" runat="server" />
                    </asp:TableHeaderCell>
                </asp:TableRow>
                <asp:TableRow>
                    <asp:TableCell style="text-align:center" ColumnSpan="2">
                        <asp:ContentPlaceHolder ID="body" runat="server" >
                        </asp:ContentPlaceHolder>
                    </asp:TableCell>
                </asp:TableRow>
                <asp:TableRow>
                    <asp:TableCell ColumnSpan="2" HorizontalAlign="Center">
                        <asp:Label ID="lblFooterText" style="text-align:center; font-weight:bold" runat="server" >
                            &nbsp;&nbsp;&nbsp; The TinyNP Project Common Footer &nbsp;&nbsp;&nbsp;
                        </asp:Label>
                    </asp:TableCell>
                </asp:TableRow>
            </asp:Table>
        </div>
    </form>
</body>
</html>

TinyNPm.Master.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using AjaxControlToolkit;

namespace TinyNP
{
    public partial class TinyNPm : System.Web.UI.MasterPage
    {
        public double tableWidth
        {
            get { return Table1.Width.Value; }
            set { Table1.Width =new Unit(value,UnitType.Pixel); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Body1.Attributes.Add("bgcolor", "burlywood");
            if (Global.igMasterPageEntryCount < 1)
            {
                lblHeaderText.Text = "The " + Global.sgcAppName + " Common Header";
                lblFooterText.Text = "The " + Global.sgcAppName + " Common Footer";
                NavCheckBox.Checked = Global.NavCheckBoxChecked;
                AlwaysVisibleNavChb();
            }
            else
            {
                if (!IsPostBack)
                {
                    NavCheckBox.Checked = Global.NavCheckBoxChecked;
                    AlwaysVisibleNavChb();
                }
            }
            Global.igMasterPageEntryCount++;
        }

        protected void Menu1_OnMenuItemClick(object sender, MenuEventArgs e)
        {
            Redirect2detectscreen(e.Item.DataPath);
        }

        protected void Redirect2detectscreen(string suDataPath)
        {
            Session["ScreenResolution"] = null;
            Global.sgCallingFrom = suDataPath;
            Response.Redirect(Global.sgCallingFrom);
        }

        protected void NavCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            AlwaysVisibleNavChb();
        }
        private void AlwaysVisibleNavChb()
        {
            AlwaysVisibleControlExtender1.Enabled = NavCheckBox.Checked;
            Global.NavCheckBoxChecked = NavCheckBox.Checked;
        }

    }
}

的Global.asax.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.SessionState;
using System.Drawing;
using System.IO;

namespace TinyNP
{
    public class Global : System.Web.HttpApplication
    {
        public const string sgcAppName = "TinyNP Project";
        private static string sCallingFrom = "~/Default.aspx";
        public static string sgCallingFrom { get { return sCallingFrom; } set { sCallingFrom = value; } }
        public static string sgHomeDir = "";
        public static Boolean NavCheckBoxChecked = true;
        public enum enumButtons { NoYes, OkOnly, OkCancel};

        //Gallery Support
        public static int[] aigPhotoSize = new int[5] { 250, 600, 1000, 1400, 1200 }; // in pixels
        public static int igInitialCustomPhotoSize = aigPhotoSize[4];
        public enum enumPhotoSizes { Smartphone, Laptop, SmallDesktop, LargeDesktop, Custom };
        public static enumPhotoSizes egPhotoSizeIndex = enumPhotoSizes.Laptop;
        public static int igSubGalleryEntryCount = 0;
        public static Boolean bgCustomDivVisible = false;
        public struct SgDynTab
        {
            public string sFolder; // Name of folder from column sFoldername in database table TNP_FOLDERS
            public int iSelFolderIndex; // Index in Folder Dropdown pointing to selected folder
            public int iSelMediaTypeIndex; // Index in Media Type Dropdown pointing to selectd media type
            public int iSelMediaID; // ID in table dbo.TNP_MEDIADATA for the selected item in the active tab
            public string sMediaType; // Name of Media Type from column sMediaType in database table TNP_MEDIATYPES
            public override string ToString()
            {
                return "SgDynTab: sFolder=" + sFolder + ", iSelFolderIndex=" + iSelFolderIndex.ToString() +
                    ", iSelMediaID =" + iSelMediaID.ToString() + ", sMediaType=" + sMediaType;
            }
            public SgDynTab(string suF, int iuSF, int iuSMT, int iuSMI, string suM)
            {
                this.sFolder = suF;
                this.iSelFolderIndex = iuSF;
                this.iSelMediaTypeIndex = iuSMT;
                this.iSelMediaID = iuSMI;
                this.sMediaType = suM;
            }
        }
        public static SgDynTab SgDyTb = new SgDynTab("",0,0,0,"");

        //Default Page support
        public static int igMasterPageEntryCount = 0;
        public static Size SizegInitWindow = new Size(600, 400);

        //Logging
        public static Boolean bgLogging = true;
        public static StreamWriter wgLog;
        public static void oLog(string logMessage)
        {
            if (bgLogging)
            {
                DateTime DNow = DateTime.Now;
                wgLog.WriteLine(DNow.ToShortDateString() + " " + DNow.ToShortTimeString() + ":"
                    + (100 + DNow.Second).ToString().Substring(1) + "."
                    + (1000 + DNow.Millisecond).ToString().Substring(1) + "-" + logMessage);
                wgLog.Flush();
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            if (bgLogging)
            {
                string sPath = Server.MapPath("~") + "/App_Data/TinyNP.log";
                wgLog = new StreamWriter(sPath, true);
                oLog("******************** Logging started for " + sgcAppName + ", log file path=`" + sPath + "` ********************");
            }
        }
        protected void Application_End(object sender, EventArgs e)
        {
            if (bgLogging)
            {
                oLog("******************** Logging ended for " + sgcAppName + " ********************");
                wgLog.Close();
            }
        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

            // Get the exception object.
            Exception exc = Server.GetLastError();

            // Handle HTTP errors
            if (exc.GetType() == typeof(HttpException))
            {
                // The Complete Error Handling Example generates
                // some errors using URLs with "NoCatch" in them;
                // ignore these here to simulate what would happen
                // if a global.asax handler were not implemented.
                if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
                    return;

                //Redirect HTTP errors to HttpError page
                Server.Transfer("~/ErrorPages/CustomError.aspx");
                return;
            }

            // For other kinds of errors give the user some information
            // but stay on the default page
            Response.Write("<h2>Global Page Error</h2>\n");
            Response.Write("<p>" + exc.Message + "</p>\n");
            Response.Write("Return to the <a href='~/Default.aspx'>" +
                "Home Page</a>\n");

            // Log the exception and notify system operators
            ExceptionUtility.LogException(exc, "DefaultPage");
            //ExceptionUtility.NotifySystemOps(exc);

            // Clear the error from the server
            Server.ClearError();
        }
        public sealed class ExceptionUtility
        {
            // All methods are static, so constructor can be private 
            private ExceptionUtility()
            { }

            // Log an Exception 
            public static void LogException(Exception exc, string source)
            {
                if (exc.InnerException != null)
                {
                    oLog("Inner Exception Type: ");
                    oLog(exc.InnerException.GetType().ToString());
                    oLog("Inner Exception: ");
                    oLog(exc.InnerException.Message);
                    oLog("Inner Source: ");
                    oLog(exc.InnerException.Source);
                    if (exc.InnerException.StackTrace != null)
                    {
                        oLog("Inner Stack Trace: ");
                        oLog(exc.InnerException.StackTrace);
                    }
                }
                oLog("Exception Type: ");
                oLog(exc.GetType().ToString());
                oLog("Exception: " + exc.Message);
                oLog("Source: " + source);
                oLog("Stack Trace: ");
                if (exc.StackTrace != null)
                {
                    oLog(exc.StackTrace);
                    oLog(" ");
                }
            }

            // Notify System Operators about an exception 
            public static void NotifySystemOps(Exception exc)
            {
                // Include code for notifying IT system operators
            }

        }
    }
}

SlideShow.aspx:

<%@ Page Title="" Language="C#" MasterPageFile="~/TinyNPm.Master" AutoEventWireup="true" CodeBehind="SlideShow.aspx.cs" Inherits="TinyNP.Media.SlideShow" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<asp:Content ID="Content1" ContentPlaceHolderID="body" runat="server">
    <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server" />
    <asp:Table runat="server" BorderWidth="0" cellpadding="0" cellspacing="0">
        <asp:TableRow>
            <asp:TableCell>
                <asp:Button ID="btnPrevious" runat="server" Text="<<" Font-Size="20" />
            </asp:TableCell>
            <asp:TableCell>
                <asp:Image ID="Image1" runat="server" Height="300" Width="300" />
                <ajaxToolkit:SlideShowExtender ID="SlideShowExtender1" runat="server" TargetControlID="Image1"
                    SlideShowServiceMethod="GetImages"
                    ImageTitleLabelID="lblImageTitle" ImageDescriptionLabelID="lblImageDescription"
                    AutoPlay="true" PlayInterval="1000" Loop="true" PlayButtonID="btnPlay" StopButtonText="Stop"
                    PlayButtonText="Play" NextButtonID="btnNext" PreviousButtonID="btnPrevious" >
                </ajaxToolkit:SlideShowExtender>
            </asp:TableCell>
            <asp:TableCell>
                <asp:Button ID="btnNext" runat="server" Text=">>" Font-Size="20" />
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell columnspan="3" HorizontalAlign="center">
                <asp:Button ID="btnPlay" runat="server" Text="Play" Font-Size="20" />
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell columnspan="3" HorizontalAlign="center">
                <br />
                <b>Name:</b>
                <asp:Label ID="lblImageTitle" runat="server" Text="Label" /><br />
                <b>Description:</b>
                <asp:Label ID="lblImageDescription" runat="server" Text="Label" />
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>
</asp:Content>

SlideShow.aspx.cs:

using System;
using System.IO;
using AjaxControlToolkit;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace TinyNP.Media
{
    public partial class SlideShow : System.Web.UI.Page
    {
        [WebMethod]
        [ScriptMethod]
        public static AjaxControlToolkit.Slide[] GetImages()
        {
            Global.oLog("SlideShow.GetImages entry");
            List<Slide> slides = new List<Slide>();
            string path = HttpContext.Current.Server.MapPath("~/i/AjaxSlideShow/");
            if (path.EndsWith("\\"))
            {
                path = path.Remove(path.Length - 1);
            }
            Uri pathUri = new Uri(path, UriKind.Absolute);
            string[] files = Directory.GetFiles(path);
            foreach (string file in files)
            {
                Uri filePathUri = new Uri(file, UriKind.Absolute);
                Slide slyde =
                new Slide {
                    Name = Path.GetFileNameWithoutExtension(file),
                    Description = Path.GetFileNameWithoutExtension(file) + " Description.",
                    ImagePath = "../i/" + pathUri.MakeRelativeUri(filePathUri).ToString()
                };
                slides.Add(slyde);
                Global.oLog("".PadLeft(8) + "Name=" + slyde.Name);
                Global.oLog("".PadLeft(12) + "Description=" + slyde.Description);
                Global.oLog("".PadLeft(12) + "ImagePath=" + slyde.ImagePath);
            }
            Global.oLog("SlideShow.GetImages exit (" + slides.Count.ToString() + " slides)");
            return slides.ToArray();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Global.oLog("SlideShow.Page_Load entry");
            Global.oLog("SlideShow.Page_Load exit");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

解决方案非常简单:只需删除asp的高度属性:Image ID =&#34; Image1&#34;在文件SlideShow.aspx中。图像的宽高比将自动保留。或者,可以保留Height属性并删除Width属性。我可以踢自己没有碰到这个。