Add HTML5 placeholder text to a textbox .net - asp.net

I have a standard input:
<asp:TextBox type="text" runat="server" id="txtSearchTerm" />
I'd like to have this render with a dynamic HTML5 placeholder. Something like:
'Code Behind
txtSearchTerm.**placeholder** = "Search " + Site.Name
So that it outputs the following HTML:
<input type="text" runat="server" id="txtSearchTerm"
placeholder="Search Site #1" />
where Site.Name = "Site #1".
txtSearchTerm.placeholder is not a property. I have it set to text and then run javascript to show/hide on focus BUT I would much rather just use the HTML5 placeholder value. How can I render this?
Please no JS/client side solutions.

You could use the Attributes collection. So you would have something like
txtSearchTerm.Attributes.Add("placeholder", "Search" + Site.Name);
or
txtSearchTerm.Attributes["placeholder"] = "Search" + Site.Name; // or Attributes("placeholder") if you're using vb.net
And if you're using resources for localization/translation:
txtSearchTerm.Attributes["placeholder"] = GetLocalResourceObject("YourLocalResourceName").ToString();

Because I find it annoying/tiresome to add all the placeholders from the code behind. You can create a new TextBox Class that inherits the WebControls TextBox and then you can add the placeholder from the CodeBehind or from the HTML Side.
TextBox.cs (Placed in Project/Controls/)
namespace Project.Controls
{
public class TextBox : System.Web.UI.WebControls.TextBox
{
public string PlaceHolder { get; set; }
protected override void OnLoad(EventArgs e)
{
if(!string.IsNullOrWhiteSpace(PlaceHolder))
this.Attributes.Add("placeholder", PlaceHolder);
base.OnLoad(e);
}
}
}
Register Control In the Web.Config:
<system.web>
<pages>
<controls>
<add tagPrefix="ext" assembly="Project" namespace="Project.Controls" />
</controls>
</pages>
</system.web>
(use whatever tag prefix you want)
Usage:
<ext:TextBox runat="server" id="SomeId" PlaceHolder="This is a PlaceHolder" />
or from the code behind
SomeId.PlaceHolder="This is a PlaceHolder";

I just put placeholder property in HTML code and works:
<asp:TextBox placeholder="hola mundo" ID="some_id" runat="server"/>

There is also the TextBoxWatermark extender included in Microsoft's Ajax Control toolkit. It's not HTML5, but it's backwards compatible (I believe).
http://www.asp.net/AjaxLibrary/AjaxControlToolkitSampleSite/TextBoxWatermark/TextBoxWatermark.aspx
<ajaxToolkit:TextBoxWatermarkExtender ID="TBWE2" runat="server"
TargetControlID="TextBox1"
WatermarkText="Type First Name Here"
WatermarkCssClass="watermarked" />

Related

Accessing web config value from asp:ListItem

I'm trying to print the value I have stored in the web config as text for a list item.
<asp:ListItem Enabled="true" Selected="true" Text="Web Only - <%$ AppSettings:SubscriptionPrice %>"
Value="web" />
will give me: Web Only - <%$ AppSettings:SubscriptionPrice %>
However, if I remove the Web Only text and do this:
<asp:ListItem Enabled="true" Selected="true" Text="<%$ AppSettings:SubscriptionPrice %>"
Value="web" />
I'll get the variable desired. Is there a way to have the text and the value from my appsettings?
You cannot do it inline that easily. Your options are:
Set the complete value in your AppSettings. (easy)
Set the value from code behind. (easy)
Lastly, if you want to be in ASPX and nothing else is acceptable, you need to write a CodeExpressionBuilder so that you can provide custom code, as follows: (may be an overkill)
here is the code expression builder
namespace Funky
{
[System.Web.Compilation.ExpressionPrefix("Code")]
public class CodeExpressionBuilder : System.Web.Compilation.ExpressionBuilder
{
public override System.CodeDom.CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, System.Web.Compilation.ExpressionBuilderContext context)
{
return new System.CodeDom.CodeSnippetExpression(entry.Expression);
}
}
}
add this web.config entry
<compilation debug="true" targetFramework="4.5">
<expressionBuilders>
<add expressionPrefix="MyCode" type="Funky.CodeExpressionBuilder"/>
</expressionBuilders>
</compilation>
finally use the code expression as follows:
<asp:ListItem Enabled="true" Selected="true" Text='<%$ MyCode: "Web Only - " + ConfigurationManager.AppSettings["SubscriptionPrice"] %>' Value="web" />
I'm not sure you can do this on page, but you can do this in your code file:
ListItem item = new ListItem();
item.Text = "Web Only - " + System.Configuration.ConfigurationManager.AppSettings["SubscriptionPrice"];
item.Value = "web";
item.Selected = true;
ListBox1.Items.Add(item);
Sorry about the earlier post.
I think you are going to have to bind the value is code.
ddl.Items.Clear()
ddl.Items.Add(New ListItem("Web Only -" & ConfigurationManager.AppSettings("SubscriptionPrice"), "Web"))

Web Forms error message: "This is not scriptlet. Will be output as plain text"

In my ASP .NET Web Forms I have the following declarative code:
<asp:TextBox runat="server" ID="txtbox" CssClass='<%=TEXTBOX_CSS_CLASS%>' />
The constant TEXTBOX_CSS_CLASS is defined in a base class that the page's code-behind class inherits from:
public class MyPageBase : Page
{
protected internal const string TEXTBOX_CSS_CLASS = "myClass";
}
The edit-time compiler however warns me that "This is not scriptlet [sic]. Will output as plain text".
True to its word, the css class is rendered as literally "<%=TEXTBOX_CSS_CLASS%>".
What does this error message mean and is there a workaround so I can still use a constant in a base class?
You cannot use <%= ... %> to set properties of server-side controls.
Inline expressions <% %> can only be used at
aspx page or user control's top document level, but can not be embeded in
server control's tag attribute (such as <asp:Button... Text =<% %> ..>).
If your TextBox is inside a DataBound controls such as GridView, ListView .. you can use: <%# %> syntax. OR you can call explicitly DataBind() on the control from code-behind or inline server script.
<asp:TextBox runat="server" ID="txtbox" class='<%# TEXTBOX_CSS_CLASS %>' />
// code Behind file
protected void Page_Load(object sender, EventArgs e)
{
txtbox.DataBind();
}
ASP.NET includes few built-in expression builders that allows you to extract custom application settings and connection string information from the web.config file. Example:
Resources
ConnectionStrings
AppSettings
So, if you want to retrieve an application setting named className from the <appSettings> portion of the web.config file, you can use the following expression:
<asp:TextBox runat="server" Text="<%$ AppSettings:className %>" />
However, above snippet isn't a standard for reading classnames from Appsettings.
You can build and use either your own Custom ExpressionBuilders or Use code behind as:
txtbox.CssClass = TEXTBOX_CSS_CLASS;
Check this link on building Custom Expression builders.
Once you build your custom Expression you can display value like:
<asp:TextBox Text="<%$ SetValue:SomeParamName %>"
ID="setting"
runat="server" />
The problem is that you can't mix runat=server controls with <%= .. %>code blocks. The correct way would be to use code behind: txtbox.CssClass = TEXTBOX_CSS_CLASS;.
This will work.
Mark up
<asp:TextBox runat="server" ID="txtbox" class='<%# TEXTBOX_CSS_CLASS %>' />
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtbox.DataBind();
}
}
But its a lot cleaner to access the CssClass property of the asp:TextBox on Page_Load

how to run asp.net code from string variable at runtime?

i have following code in a String variable at run-time
<form runat="server">
<asp:textbox runat="server"
ID="a1"
Text="enter text here"
/>
<asp:button runat="server"
Text="enter text here"
/>
<br />
</form>
so how can i run it to at run time on a new page by clicking on some button or so?
earliest help will be highly appreciated.
You mentioned loading from a text file. I think you should review usercontrols. It is the preferred method to load asp.net content and controls from an included file.
http://msdn.microsoft.com/en-us/library/y6wb1a0e(v=vs.100).aspx
Put this code into a user control, and pass the control name as a string instead.
void Page_Init(object sender, System.EventArgs e)
{
//your string
string controlName = "TempControl_Samples1.ascx.cs";
// instantiate usercontrol object
MyControl myControl1 = (MyControl)LoadControl(controlName);
PlaceHolder1.Controls.Add(myControl1);
}

HTTPContext.Current.User.Identity.Name not working inside a control?

I have a label and I want to set text of this label to
HTTPContext.Current.User.Identity.Name
So I wrote
Text = '<%=HTTPContext.Current.User.Identity.Name %>'
but it doesn't work, however when I wrote this outside of the lable for example:
<h2>
<%=HTTPContext.Current.User.Identity.Name %>
</h2>
it works.
<asp:Label ID="lbUserName"
runat="server"
Text='<%# HttpContext.Current.User.Identity.Name %>'
/>
in Page_Load
if (!Page.IsPostBack )
{
lbUserName.DataBind();
}
use label like this
<asp:label id="lblx" runat="server" ><%= HTTPContext.Current.User.Identity.Name %></asp:label>
To bind the text like this you will have to create your own custom expression builder.
First, add such class to your namespace:
using System.Web.Compilation;
using System.CodeDom;
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}
Next step is adding this to your web.config file:
<compilation debug="true">
<expressionBuilders>
<add expressionPrefix="Code" type="YourNameSpace.CodeExpressionBuilder"/>
</expressionBuilders>
</compilation>
Then finally this should work:
<asp:Label id="YourLabel" runat="server" Text='<%$ Code:HttpContext.Current.User.Identity.Name %>' />
Complicated way to achieve something simple, but this will allow you to use the syntax you want throught your whole project so might worth the extra effort.
Reference.

Public Properties in Code Behind of a User Control

In a regular .aspx page, you can access public properties from the codebehind. Is there any way to do a similar thing in a user control. For example, in the following code 'List' is public property of the codebehind of the user control and yet it is not accessible.
<% foreach (TripTeam team in List) { %>
<div>
<label><%= team.Name %></label>
</div>
<%} %>
You can access the public properties of a UserControl from your .aspx page. Here's an example
<script runat="server">
public string Caption { get { return _caption.Text; } set { _caption.Text = value; } }
public string Text{ get { return _tb1.Text; } set { _tb1.Text = value; } }
<div>
<asp:Label ID="_caption" runat= "server" class="caption" /><br />
<asp:TextBox ID="_tb1" runat="server" CssClass="textBox" Width="25px" />
Then on your aspx page, you can set the Text and Caption properties within your user control:
<uc1:CaptionText ID="ct1" runat="server" Caption="User name" />
You need to say 'userControlId.List' to access the property when accessing a property in the control from a page which uses the control.

Resources