Asp.net, directly assigning properties from value? - asp.net

Is there a way to express
<% objControl.ObjProp=ObjVar; %>
<my:Control ID="objControl" runat="server" />
As something like this, in one line? And without passing ObjVar as a string?
<my:Control ID="objControl" runat="server" ObjProp=ObjVar />

Unless you're in a databound context, no there's no simple way to do this. If it is a databound context (Like in a repeater/gridview) you can simply go ObjProp='<%# ObjVar %>', but outside that context you can't do it inline unfortunately.

use it like
<my:Control ID="objControl" runat="server" ObjProp="<%# ObjVar %>" />

As fyjham has mentioned, you need to do this in a databound context with the <%# %> syntax. If you are trying to set the property dynamically then your other option is to set it within the server side parent's onload code behind method.

What is ObjVar? If it's a static value, you can just add the attribute tag to the control element like so....
<my:Control ID="objControl" runat="server" MyCustomBooleanProperty="true" />
If it's a member variable of the page containing the control, then I'd do so in the code behind...
protected Page_Init()
{
this.objControl.ObjProp = this.ObjVar;
}
If you're databinding to the control, then the others are correct where you use the databinding context.
<my:Control ID="objControl" runat="server" ObjProp=<%#Eval("ObjVar")%> />

Related

User Control Static Name Option?

I know there is a way to force asp web user controls (ascx) to use static ID's so they don't get appended with all the appended naming garbage...but is there way to do the same for the"name" attribute? Specifically, in this case, for DDL's? JQuery needs a specific name and I need to stop .NET from doing this.
Not possible in ASP.Net for now ... I've found this combination to be an acceptable solution.
Add the ClientIDMode="Static" to the control:
<asp:HiddenField ID="HiddenField1" runat="server" ClientIDMode="Static" />
Using JQuery, on document ready, set the name attribute on the control to the value of its id:
$(document).ready(function () {
// alert($("#HiddenField1").attr("name"));
$("#HiddenField1").attr("name", "HiddenField1");
// alert($("#HiddenField1").attr("name"));
});
Try adding ClientIDMode="Static" to the control tag.
<asp:FileUpload ID="FileUpload1" runat="server" ClientIDMode="Static" />

Bind control's ID property to object property

I have the following repeater control, which is bound to collection of DashboardPage objects. DashboardPage has the following properties: Name, Pagenumber .
<asp:Repeater ID="reportPages" runat="server">
<ItemTemplate>
<asp:ImageButton runat="server" onclick="ImageButton_Click"
ImageUrl="<%# GetImagePath(Container.DataItem) %>"
onmouseover="<%# GetMouseOverEventString(Container.DataItem) %>"
onmouseout="<%# GetMouseOutEventString(Container.DataItem) %>"
/>
</ItemTemplate>
<SeparatorTemplate>
</SeparatorTemplate>
</asp:Repeater>
I want to bind ImageButton's ID property to Name property of DashboardPage object, something like this
ID="<%# Eval('Name') %>"
But an exception is thrown:
The ID property of a control can only be set using the ID attribute in the tag and a simple value.
I need the ID property of the image, because I have a client side script which changes the image, using the it's ID. Is there a way around this?
Thanks for replies
Regards
Gagik Kyurkchyan
Since you have found you cannot dynamically set the ID of a server control you need to find an alternative way of referencing your image using JavaScript. There are three ways I can think of:
Set the CssClass property of the control and use that instead. It's a little more inefficient to find a control by class rather than ID using DOM, but that is probably negligible in the real world.
Wrap your image in a standard DIV. and set the ID on the container DIV. You can then use something like jQuery to go $("#divid img")...
Use a standard <img> tag (with no runat="server") rather than an asp:Image control. You can then set the ID on that without issue.
You can use ItemDataBound to set the ID.
CODEBEHIND:
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var textbox = e.Item.FindControl("myTextBox");
textbox.ID = "myTextBox" + (e.name).toString(); /*ToString() method can be unnecessary in some cases.*/
}
REPEATER:
<asp:Repeater ID="myRepeater" runat="server" OnItemDataBound="BehaviorCustomizeRepeater_ItemDataBound">
/*other stuffs*/
</asp:Repeater>

ASP.NET Repeater question

I have a repeater control and under the ItemTemplate, I have Image control. Anyway the old
How can I set the ImageUrl programatically?
Anyway, the old html code I have was like this:
<ItemTemplate>
<img src="<%# Eval("ImageSource") %>" alt="" />
</ItemTemplate>
But I want to check if the image exists in directory or not then I can setup with temp image.
I have a code but .. it's not really working so there's no sense of showing it here. Can you guys help me? Should I use ItemCreated or ItemDataBound event?
In the xml side in the template, you need to call a method directly.
<asp:Image runat="server" ID="myImg" ImageUrl='<%# MyImageUrlFunction(Eval("DataFieldName").ToString()); %>' />
You need a corresponding method in the code behind defined publicly:
public string MyImageUrlFunction(string field)
{
// put some logic here to determine url
return imageUrl;
}
In your ItemDataBound, do something like:
protected void rpt_ItemDataBound(object sender, RepeaterEventArgs e)
{
HtmlImage img = (HtmlImage)e.Item.FindControl("img");
string imageUrl = (string)DataBinder.Eval(e.Item.DataItem, "ImageSource");
if (File.Exists(imageUrl))
img.Src = imageUrl;
}
That's System.Web.UI.HtmlControls.HtmlImage, System.Web.UI.DataBinder and System.IO.File.
ItemDataBound. You can get the control reference through the current item's findcontrol event, and then check to see that the image exists. You can get the file path using Server.MapPath("~/images/test.png"), and then if it doesn't, inject your own.
You can also use a public method that the client-side markup can call, pass in the URL, and provide a default if it doesn't exist.
HTH.
<ItemTemplate>
<asp:Image ImageUrl='<%# System.IO.File.Exists(Eval("ImageSourceProperty").ToString()) ? Eval("ImageSourceProperty").ToString() : TemporaryImagePath %>' runat="server" />
</ItemTemplate>
for the Error
The server tag is not well formed
You should remove extra space in your code!
<%# System.IO.File......%>
should be <%#System.IO.File......%>

problem assigning declarative values in asp:hyperlink. error: this is not scriptlet. will output as plain text

I am trying to do this:
<asp:HyperLink NavigateUrl='<%= WebContext.RootUrl %><%= WebContext.CurrentUser.UserName %>' runat="server" Text='<%= GetProfileImage(WebContext.CurrentUser.AccountId) %>'></asp:HyperLink>
But am getting the error:
this is not scriptlet. will output as
plain text.
when I mouse over my declarative statements.
Any ideas? Thanks.
You cannot use <%= ... %> literals to set properties of server-side controls.
Instead, you can use a normal (client-side) <a> tag, like this:
<%= GetProfileImage(WebContext.CurrentUser.AccountId) %>
If GetProfileImage doesn't return HTML tags, make sure to escape it.
You can use data binding syntax <%# %>. Just be sure that your hyperlink is either in a databound control, such as a ListView item template, or that you explicitly call DataBind() on the control from code-behind.
You can still populate an <asp:HyperLink> if you provide the ID and runat="server" properties. You can then set any property of the HyperLink from code-behind.
ASP Code:
<asp:HyperLink ID="myLink" runat="server"/>
Code-behind:
public void Page_Init()
{
myLink.NavigateURL = WebContext.RootUrl + WebContext.CurrentUser.UserName;
myLink.Text = GetProfileImage(WebContext.CurrentUser.AccountId);
}
<a href='<%= WebContext.RootUrl %><%= WebContext.CurrentUser.UserName %>'><%= GetProfileImage(WebContext.CurrentUser.AccountId) %></a>

Can I use <%= ... %> to set a control property in ASP.NET?

<asp:TextBox ID="tbName" CssClass="formField" MaxLength="<%=Constants.MaxCharacterLengthOfGameName %>" runat="server"></asp:TextBox>
The code above does not work. I can set the MaxLength property of the textbox in the code behind but i rather not. Is there away I can set the MaxLength property in the front-end code as above?
You could use DataBinding:
<asp:TextBox
ID="tbName"
CssClass="formField"
MaxLength="<%# Constants.MaxCharacterLengthOfGameName %>"
runat="server">
</asp:TextBox>
and in your code behind Page_Load call:
tbName.DataBind();
or directly databind the page:
this.DataBind();
The <%= expression %> syntax is translated into Response.Write(expression), injecting the value of expression into the page's rendered output. Because <%= expression %> is translated into (essentially) a Response.Write these statements cannot be used to set the values of Web control properties. In other words, you cannot have markup like the following:
<asp:Label runat="server" id="CurrentTime" Text="<%= DateTime.Now.ToString() %>" />
Source: https://web.archive.org/web/20210513211719/http://aspnet.4guysfromrolla.com/articles/022509-1.aspx
Try to use custom expression builder:
// from http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : System.Web.Compilation.ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}
And then use it like
<asp:TextBox ID="tbName" CssClass="formField" MaxLength="<%$ Code: Constants.MaxCharacterLengthOfGameName %>" runat="server"></asp:TextBox>
As Ropstah said, it isn't going to work with the <%= expression %> syntax.
But you could probably use databinding, which just requires that you use the <%# expression %> syntax and then call MyTextBox.Databind in CodeBehind.
Of course, at that point it might be more clear to just do the whole operation in CodeBehind.
Another alternative: if you really want this to be declarative, you could get away from the Label and embed your expression in a span tag.That way you still get to apply CSS, etc and I think the <%= expression %> syntax would work.
Why don't you just set it in the Page_Init callback function in the code behind?
This example is geared towards getting the max length from underlying sql types in linq. But you should be able to customise it to your needs
http://blog.binaryocean.com/2008/02/24/TextBoxMaxLengthFromLINQMetaData.aspx
It looks like you want to be able to control the max length of a specific type of text box from a single location so that if that max length needs to change, you only need to change it in one place.
You can accomplish this by using a skin file. You set the max length in the skin file as you would normally and then any textbox that uses that max length would use the skin. If the length changes then you only need to change the skin file.
You can do it with databinding
<asp:TextBox
ID="tbName"
CssClass="formField"
MaxLength='<%# Constants.MaxCharacterLengthOfGameName %>'
runat="server" />
Then in the code behind
protected void Page_Load(object sender, EventArgs e) {
Page.DataBind();
}
You can embed "normal" code in the .aspx file if you so want, like:
<%
tbName.MaxLength = Constants.MaxCharacterLengthOfGameName
%>
<asp:TextBox ID="tbName" CssClass="formField" runat="server"></asp:TextBox>
This harkens back to an older style "classic" ASP way of doing this.

Resources