Setting value in html control in code behind without making server control
<input type="text" name="txt" />
<!--Please note I don't want put 'runat="server"' here to get the control in code behind-->
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//If I want to initlize some value in input, how can I set here
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Request["txt"] // Here I am getting the value of input
}
This answer comes from memory, so I apologize if it's slightly off.
What you can do is use an ASP.NET inline expression to set the value during the loading of the page.
First, add a property in the code-behind of your page.
protected string InputValue { get; set; }
In the Page_Load event, set the value of the property.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.InputValue = "something";
}
}
Finally, add an inline expression in your page markup like this:
<input type="text" name="txt" value="<%= this.InputValue %>" />
This will let you set the value of the input element without making it a server-side tag.
Elements that are not set runat="server" are considered plain text and collected into as few Literal objects as possible (one between each serverside control). I suppose if you really really wanted to, you could try to find the correct Literal (or maybe LiteralControl) object in Page.Controls, and modify it, but I'd definately recommend against it.
What's so terrible about setting it runat="server" ?
And yes, of course you can also use <%= %>. Embedded code blocks. They're evaluated at Render time, so it should be relatively safe to do so.
Add an expression in your page like this:
<input class="field" id="locality" name="loc" value="<%= this.inputtypeCT %>"/>
Add a property in the code-behind of your page:
protected string inputtypeCT;
In the Page_Load event, set the value of the property:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.inputtypeCT = "test"
}
}
<input type="text" name="txt" value="<%= System.Web.HttpUtility.HtmlEncode(this.InputValue) %>" />
Add runat server
or use Asp controls like below
<asp:TextBox type="text" runat="server" class="demoHeaders" id="datepicker" ClientIDMode="Static" Text=""/>
Also make sure that you used ClientIDMode="Static" for the naming of control to be in clinet as like server.
Enjoy!
Related
I've just written a ASP .NET wrapper for jQuery UI control as user control. It can be used like this:
<ui:DatePicker ID="startDate" runat="server" LabelText="Start Date:" />
Currently I set initial value of this control in Page_Load handler, just like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
startDate.Value = DateTime.Now.AddMonths(-2);
}
}
But I thought that it would be nice to move initialization code to markup. Yet I can't work out is how to set initial value of this control using inline tag, for instance:
<ui:DatePicker ID="startDate" Value='<%= DateTime.Now.AddMonths(-2) %>' runat="server" LabelText="Start Date:" />
I have a property:
public DateTime? Value
{
get
{
DateTime result;
if (DateTime.TryParse(dateBox.Text, out result))
{
return result;
}
return null;
}
set
{
dateBox.Text = value != null ? value.Value.ToShortDateString() : "";
}
}
I've tried different inline tags combinations, and I always get a compilation error. Is there a way to achieve it with inline tags?
You will need to put the actual date representation in the property. The reason is that some properties of Asp.Net controls also behave like that e.g. the visible property of a TextBox cannot be set like <asp:TextBox runat="server" Visible='<%= true %>'></asp:TextBox>
<ui:DatePicker ID="startDate" Value='20/10/2012' runat="server" LabelText="Start Date:" />
Or set the value from your Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
startDate.Value = DateTime.Now; //initialize DatePicker
}
}
I found these link:
Why will <%= %> expressions as property values on a server-controls lead to a compile errors?
Set Visible property with server tag <%= %> in Framework 3.5
I want to display image in img control.
Asp code:
<asp:Image id="id" src='<%# Eval("Item.SmallPicPath") %>' Runat="Server" >
C# code:
public void Page_Load(Object sender, EventArgs e)
{
Glasses item=GetItemByID(GlassesID) //retrive record from data base
}
Glasses is a class that have property SmallPicPath.
I try to display image but i get error any idea how to fix it?
Thank you in advance!
The approach you're trying to use is based on databinding, which generally isn't good for a single image.
Instead, try something like this markup:
<asp:Image id="MyImageId" runat="server">
Then, in your code behind:
public void Page_Load(Object sender, EventArgs e)
{
Glasses item = GetItemByID(GlassesID); //retrive record from data base
this.MyImageId.ImageUrl = item.SmallPicPath;
}
If you still want to use databinding for some reason, something like this should work (although there's a performance cost compared to the other approach):
<asp:Image id="MyImageId" runat="server" ImageUrl="<%# item.SmallPicPath %>">
Code-behind:
public Glasses item;
public void Page_Load(Object sender, EventArgs e)
{
this.item = GetItemByID(GlassesID); //retrive record from data base
this.MyImageId.DataBind();
}
Databinding is an optional operation; you need to call DataBind() on the control (or its parent) to make it happen.
You only need "Eval()" in cases that involve a data container (usually via a DataSource) -- which this one doesn't.
<asp:Image id="id" ImageUrl='<%# Eval("Item.SmallPicPath") %>' Runat="Server" >
The Eval expression might not be Item.SmallPicPath. If your data object is type of Glass and this type has SmallPicPath property, then use Eval("SmallPicPath").
I have to add a Page's variable into a ItemTemplate but dont know how.
For example:
<rad:RadMenuItem ID="f" runat="server" Text="Products">
<ItemTemplate>
<div class="pitem"><%= MyText %></div>
</ItemTemplate>
</rad:RadMenuItem>
The MyText variable does exist in the context and has value but the text does not show up
Another question:
How can I add MyText to the ASP.NET page like the following?
<asp:Button Text="<%=MyText%>" .../>
I dont want to edit the code like btn.Text=MyText, just want to do that on the .aspx file as required.
Answers to second question. (Btw, you should only ask one question at a time here on Stack Overflow.)
You could use
<asp:Button Text="<%# MyText %>" />
if you call DataBind() in you code behind.
public void Page_Init(object sender, EventArgs e)
{
DataBind();
}
If the databind is expensive, I believe you could use this code, so that you only call it once, and then save the values in the ViewState.
public void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataBind();
}
}
First I'll apologize for the unclear title of my question. I wasn't sure how to succinctly describe my problem in a title.
I have a hidden field in my .aspx
<input type="hidden" name="hid1" value="0" />
I want to set the value of this field during the page load event, and if it is not a postback.
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
// This doesn't work!
Request.Form["hid1"] = "1";
}
if (Page.IsPostBack) {
// This DOES work!
Request.Form["hid1"] = "1";
}
}
The problem is that the Request doesn't contain the hidden field in the Form array during the page load event when it's not a postback (ie - the first time the page is hit). Subsequent hits to the page (ie - postbacks) result in the Form array containing the hidden field.
I'm sure that it has to do with the lifecycle of the page, but what I really need to know is how do I set the hidden field during the page load event and when it is not a postback?
EDIT:
I really, really don't want to incorporate the runat="server" attribute!
You could define a property in your page class and then modify the property value in your code:
protected string HiddenFieldValue { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
HiddenFieldValue = "postback";
else
HiddenFieldValue = "not postback";
}
Then define the hidden form field like this so that it's value is set to the property value:
<input type='hidden' id='hidden1' value='<%=HiddenFieldValue %>' />
If you only want to set the value form the property during a postback or non-postback you could add the condition as well:
<input type='hidden' id='hidden1' value='<% if(IsPostBack) { %> <%=HiddenFieldValue%> <% } %>' />
Try converting the input into a HiddenField control (or, at least, a runat="server" input), and reference it by it's ID, rather than through Request.Form.
Instead of:
<input type="hidden" name="hid1" value="0" />
try this:
<asp:HiddenField runat="server" ID="hid1" />
Then in your Page_Load()
hid1.Value = "whatever...";
It will be visible both before and after postback when you declare it in this manner.
Why don't you make it a server control by setting 'runat="server"' on the input control? Then it will be accessible from your code behind, and you will be able to set the value during the first page load.
why dont you access that field through a style class and use runat server=?
This works:
<span value="<%= this.Text %>" />
This doesn't work:
<asp:Label Text="<%= this.Text %>" runat="server" />
Why is that?
How can I make the second case work properly, i.e., set the label's text to the value of the "Text" variable?
Use Data binding expressions
<asp:Label ID="Label1" runat="server" Text="<%# DateTime.Now %>" ></asp:Label>
Code behind,
protected void Page_Load(object sender, EventArgs e){
DataBind();
}
you can do this
<asp:Label ID="Label1" runat="server" ><%= variable%></asp:Label>
You will need to set the value of the server control in code
First of all, assign an ID to the label control so you can access the control
<asp:Label ID="myLabel" runat="server" />
Then, in your Page_Load function, set the value of your labels 'Text' field
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = 'Whatever you want the label to display';
}
This function will be in your code behind file, or, if you are not using the code behind model, inside your aspx page you will need
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = 'Whatever you want the label to display';
}
</script>
Good luck.
In my code i am using something like this easily but in the databound control like ListView Item template
<asp:HyperLink ID="EditAction" class="actionLinks" Visible='<%#Eval("IsTrue").ToString() != "True"%>' runat="server" NavigateUrl='<%# Eval("ContentId","/articles/edit.aspx?articleid={0}")%>' />
But when i tried to use outside the databound control using <%# .. %>, it simply doesn't work.
You can easily do with
My href
But for server controls, and outside of databound control. We need to call DataBind() in pageload event explicitly
<asp:Hyperlink ID="aa" NavigateUrl='<%#myHref%>' >
Not sure how to mark this as such, but this is a bit of a duplicate. See this thread.
I don't think embedding code in to your markup will really make your markup any clearer or more elegant.
<asp:Label> is compiling at runtime and converting to html tags. You can set text with codebehind or like this:
<asp:Label id="Text1" runat="server" />
<% Text1.Text = this.Text;%>
UPD: Seems like my variant doesnt work, this is better:
protected void Page_Load(object sender,EventArgs e)
{
Text1.Text = this.Text;
}
Just pitching this little nugget in for those who want a good technical breakdown of the issue -- https://blogs.msdn.microsoft.com/dancre/2007/02/13/the-difference-between-and-in-asp-net/
I think the crux is in pretty decent agreement with the other answers:
The <%= expressions are evaluated at render time
The <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called.
<%# expressions can be used as properties in server-side controls. <%= expressions cannot.