2008-11-04 43 views
9

Tengo un botón de imagen. Quería agregar un texto "Buscar" en él. No puedo agregarlo porque la propiedad "imagebutton" en VS 2008 no tiene control de texto. ¿Alguien puede decirme cómo agregar texto a un botón de imagen?Texto en un botón de imagen en C# asp.net 3.5

<asp:ImageButton ID="Searchbutton" runat="server" AlternateText="Search" 
     CssClass="bluebutton" 
     ImageUrl="../Graphics/bluebutton.gif" Width="110px" 
     onclick="Searchbutton_Click"/> 

Respuesta

20
<button runat="server" 
    style="background-image:url('/Content/Img/stackoverflow-logo-250.png')" > 
    your text here<br/>and some more<br/><br/> and some more .... 
    </button> 
+0

¿Todavía puede utilizar "onclick =" u otras opciones de ASP.NET cuando se rinden

+0

@TheChristopher: seguro :) (bueno, por lo que puedo recordar; p) – leppie

+4

Para aclarar, no es un clic cuando se utiliza el botón, es ServerClick. – Peter

6

No se puede hacer eso con ImageButton.

Sin embargo, puede usar un simple Button, configurar el texto y agregar una imagen de fondo (bluebutton.gif) usando CSS para lograr el efecto deseado.

0

No creo que pueda escribir texto en un control ImageButton de ASP.NET. Puede generar imágenes sobre la marcha si eso es lo que necesita y escribir el texto de su código, pero será demasiado complicado, use el botón normal con CSS, a menos que su imagen no pueda ser generada por CSS.

0

También puede hacer esto utilizando un asp: Label, así:

<style type="text/css"> 
    .faux-button 
    { 
     cursor:pointer; 
    } 
</style> 

<div class="faux-button"> 
    <asp:ImageButton ID="ibtnAddUser" 
     runat="server" 
     ImageUrl="~/Images/add.gif" 
     AlternateText="Add a user image" /> 
    <asp:Label ID="lblAddUser" 
     runat="server" 
     Text="Add User" 
     AssociatedControlID="imgClick" /> 
</div> 
6

Esta punta de dotnetslave.com trabajó para mí:

<asp:LinkButton 
    CssClass="lnkSubmit" 
    ID="lnkButton" 
    runat="server">SUBMIT</asp:LinkButton> 

a.lnkSubmit:active 
{  
    margin:0px 0px 0px 0px; 
    background:url(../../images/li_bg1.jpg) left center no-repeat; 
    padding: 0em 1.2em; 
    font: 8pt "tahoma"; 
    color: #336699; 
    text-decoration: none; 
    font-weight: normal; 
    letter-spacing: 0px; 

}

1

No es posible agregar texto dentro de un botón de imagen. También me he enfrentado al mismo problema. Mi solución fue usar un botón de enlace en lugar de un botón de imagen. Solo agregar la imagen en la etiqueta de estilo debería funcionar.

0

Me doy cuenta de que esta es una publicación anterior, pero recientemente resolví este mismo problema.

creé un control de servidor ImgButton para hacer esto:

<button> <img src="button_icon.png" /> Caption Text </button> 

El uso de CSS con el estilo de una imagen de fondo tiene algunos inconvenientes, principalmente:

  • El texto tiende a superponerse a la imagen a menos que obtenga inteligente con imagen alineada a la izquierda y texto alineado a la derecha (lo cual es inconveniente si aplica un lenguaje RTL a la mezcla)
  • La imagen es una imagen de fondo y no aparece "en el botón" cuando hacemos clic el botón que no consigue "empuja hacia abajo", el mismo que el texto

Voy a tratar de insertar el código aquí, pero también tienen el código fuente completo y los ejemplos aquí: Button with Img tag and Caption Text

ImgButton.cs:

[DefaultProperty("Text")] 
[DefaultEvent("Click")] 
[ToolboxData("<{0}:ImgButton runat=server></{0}:ImgButton>")] 
public class ImgButton : WebControl, IPostBackEventHandler 
{ 
    #region Public Properties 

    public enum ImgButtonStyle 
    { 
     Button, 
     Anchor 
    } 

    [Bindable(true)] 
    [Category("Appearance")] 
    [DefaultValue("")] 
    [Localizable(true)] 
    public string Text 
    { 
     get 
     { 
      String s = (String)ViewState["Text"]; 
      return ((s == null) ? String.Empty : s); 
     } 

     set 
     { 
      ViewState["Text"] = value; 
     } 
    } 
    [EditorAttribute(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(UITypeEditor))] 
    public string ImgSrc { get; set; } 
    public string CommandName { get; set; } 
    public string CommandArgument { get; set; } 
    [EditorAttribute(typeof(System.Web.UI.Design.UrlEditor), typeof(UITypeEditor))] 
    public string NavigateUrl { get; set; } 
    public string OnClientClick { get; set; } 
    public ImgButtonStyle RenderStyle { get; set; } 
    [DefaultValue(true)] 
    public bool UseSubmitBehavior { get; set; } 
    [DefaultValue(true)] 
    public bool CausesValidation { get; set; } 
    public string ValidationGroup { get; set; } 
    [DefaultValue(0)] 
    public int Tag { get; set; } 

    #endregion 

    #region Constructor 

    public ImgButton() 
    { 
     Text = "Text"; 
     ImgSrc = "~/Masters/_default/img/action-help.png"; 
     UseSubmitBehavior = true; 
     CausesValidation = true; 
    } 

    #endregion 

    #region Events 

    // Defines the Click event. 
    public event EventHandler Click; 
    public event CommandEventHandler Command; 

    protected virtual void OnClick(EventArgs e) 
    { 
     if (Click != null) 
     { 
      Click(this, e); 
     } 
    } 

    protected virtual void OnCommand(CommandEventArgs e) 
    { 
     if (Command != null) 
     { 
      Command(this, e); 
     } 
     RaiseBubbleEvent(this, e); 
    } 

    public void RaisePostBackEvent(string eventArgument) 
    { 
     if (CausesValidation) 
     { 
      Page.Validate(ValidationGroup); 
      if (!Page.IsValid) return; 
     } 
     OnClick(EventArgs.Empty); 
     if (!String.IsNullOrEmpty(CommandName)) 
      OnCommand(new CommandEventArgs(CommandName, CommandArgument)); 
    } 

    #endregion 

    #region Rendering 

    // Do not wrap in <span> tag 
    public override void RenderBeginTag(HtmlTextWriter writer) 
    { 
     writer.Write(""); 
    } 

    protected override void RenderContents(HtmlTextWriter output) 
    { 
     string click; 
     string disabled = (Enabled ? "" : "disabled "); 
     string type = (String.IsNullOrEmpty(NavigateUrl) && UseSubmitBehavior ? "submit" : "button"); 
     string imgsrc = ResolveUrl(ImgSrc ?? ""); 

     if (String.IsNullOrEmpty(NavigateUrl)) 
      click = Page.ClientScript.GetPostBackEventReference(this, ""); 
     else 
      if (NavigateUrl != null) 
       click = String.Format("location.href='{0}'", ResolveUrl(NavigateUrl)); 
      else 
       click = OnClientClick; 

     switch (RenderStyle) 
     { 
      case ImgButtonStyle.Button: 
       if (String.IsNullOrEmpty(NavigateUrl) && UseSubmitBehavior) 
       { 
        output.Write(String.Format(
         "<button id=\"{0}\" {1}class=\"{2}\" type=\"{3}\" name=\"{4}\" title=\"{5}\"><img src=\"{6}\" alt=\"{5}\"/>{7}</button>", 
         ClientID, 
         disabled, 
         CssClass, 
         type, 
         UniqueID, 
         ToolTip, 
         imgsrc, 
         Text 
        )); 
       } 
       else 
       { 
        output.Write(String.Format(
         "<button id=\"{0}\" {1}class=\"{2}\" type=\"{3}\" name=\"{4}\" onclick=\"javascript:{5}\" title=\"{6}\"><img src=\"{7}\" alt=\"{6}\"/>{8}</button>", 
         ClientID, 
         disabled, 
         CssClass, 
         type, 
         UniqueID, 
         click, 
         ToolTip, 
         imgsrc, 
         Text 
        )); 
       } 
       break; 

      case ImgButtonStyle.Anchor: 
       output.Write(String.Format(
        "<a id=\"{0}\" {1}class=\"{2}\" onclick=\"javascript:{3}\" title=\"{4}\"><img src=\"{5}\" alt=\"{4}\"/>{6}</a>", 
        ID, 
        disabled, 
        CssClass, 
        click, 
        ToolTip, 
        imgsrc, 
        Text 
       )); 
       break; 
     } 
    } 

    public override void RenderEndTag(HtmlTextWriter writer) 
    { 
     writer.Write(""); 
    } 

    #endregion 
} 

Aquí es el CSS que utilizo en mis botones (donde pongo "icono" en la propiedad CssClass del botón):

button.icon 
{ 
    cursor: pointer; 
} 

button.icon img 
{ 
    margin: 0px; 
    padding: 0px 5px 0px 5px; 
    vertical-align: middle; 
} 
0

Si usa un botón de enlace, puede agregar un botón de arranque y luego agregar texto a través de la propiedad CSS "después".

LinkButton:

<asp:LinkButton id="download" CssClass="btn btn-primary" Text="Download" OnCommand="OnButtonClick" CommandName="Download" runat="server"> 
       <span aria-hidden="true" class="glyphicon glyphicon-download-alt"></span></asp:LinkButton> 

CSS:

#MainContent_download:after{ 
content: "Download"; 
padding-left: 5px; 

}

Cuestiones relacionadas