Using Code Nuggets as property values - asp.net

I have the following code
<asp:Content ID="Content1" runat="server">
<asp:Label runat="server" ID="Label1" Text="<%= MyHelperClass.Value%>"></asp:Label>
<%= MyHelperClass.Value%>
</asp:Content>
The Label doesn't work, it has the Text <%= MyHelperClass.Value%> the next row returns the expected value.
Question: can i use those code nuggets to set values of the property of an control?

Why it's working outside and not with Control?
Well <%= %> is called Content Code Nuggets because they inject content in the html which is sent by server to browser. It does the work of Reponse.Write. We use this mainly to call any code written in code behind file for example, you have a simple method in your code behind:-
public string UserCity()
{
return "London";
}
Then you can call it from aspx page like this:-
You live in <%= UserCity() %>.
Content code nuggets used to inject the html to response at the last in PreRender event and thus it's called late binding. This is the main reason why it is NOT working with your control.
How to fix this?
You can use the data binding code nuggets (<%# %>). These are used with DataBound controls but you can force the Page's DataBound or control's DataBound method to bind your control like this:-
<asp:Label runat="server" ID="Label1" Text="<%# MyHelperClass.Value%>"></asp:Label>
Call DataBind method in code behind:-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Page.DataBind();
}
}

Related

Call method in ListView EmptyDataTemplate

I have a simple ListView with an EmptyDataTemplate. In the EmptyDataTemplate, there is a LinkButton whose Visble property value is an expression that calls a method in my code behind. The problem is that the LinkButton is always visible regardless of whether the method returns true or false (my method isn't being called as I even set a breakpoint on it). Anyone come across this? What's happening here?
e.g.
<asp:ListView ID="peopleListView" runat="server" ...>
...
<EmptyDataTemplate>
Sorry, no people to view.<br />
<asp:LinkButton ID="newButton" runat="server" Visible='<%# EditPermitted() %>'>New Record</asp:LinkButton>
</EmptyDataTemplate>
</asp:ListView>
In the code behind, I have the method:
protected bool EditPermitted()
{
return false;
}
I don't think you can put scriplets <% %> inside of server controls.
You need to grab the RowDataBound event, and set the link button's visibility there
void gridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.EmptyDataRow) {
LinkButton lb = e.Row.FindControl("newButton");
lb.Visible = EditPErmitted();
}
}
You can't use code blocks like <% ... %> or <%= ... %> inside the attributes of server controls. Only data binding blocks like <%# ... %>. But you can use code blocks inside your EmptyDataTemplate, in this case a simple if statement should work:
<EmptyDataTemplate>
<% if(EditPermitted()) { %>
<asp:LinkButton ID="newButton" runat="server" ... />
<% } %>
</EmptyDataTemplate>

Using same form on multiple pages?

I am writing an application, and I have a user form, which will be the same for the users and the administrators on different pages.
I want to only create the form once, and then be able to put it on two different aspx files.
I tried it with the "control", but it then gets really complicated trying to access fields on the control from the aspx page to do the calculation, etc.
is there another way to do this? creating a form in one place, be able to add it to any aspx page, and have easy access to it's controls?
It's not very difficult at all. You can provide an accessor method or make the control inside public.
Example: A page which displays the contents of a TextBox inside a control, when a button is pressed.
Control
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Page
<form runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<Test:Control ID="ctlTest" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
Code (If TextBox1 is public)
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = ctlTest.TextBox1.Text;
}
Or you could have, in the code of the control
public string GetText()
{
return TextBox1.Text;
}
And in the aspx code page
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = ctlTest.GetText();
}
What is so difficult about that?!
you have to create MasterPage:
http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx
so that you can share common controls between pages. Master pages can be nested, too. You can access controls on master page from child page via Master.FindControl("abc")
EDIT: it seems that you want to reuse common piece of functionality, then you might want to use user control, like in this example:
http://msdn.microsoft.com/en-us/library/3457w616.aspx
you created the control, and do not use findControl() method to access the control that inside you UserControl, that is not feasible or proper solution.
Better to use Properies. Define Properties, so your control can be generalised and you can use that on multiple pages.

problems with binding <%# in Custom Control

so I've finally started building custom controls instead of using functions which return chunks of HTML ;) But I'm running into a problem. I want to pass parameters to the control, say, "X":
<some:MessageControl runat="server" X=<%# "asd" %> />
My code behind looks like this:
public partial class MessageControl : System.Web.UI.UserControl
{
String x = "";
public String X
{
get { return x; }
set { x = value;}
}
}
When I output the value of x in the control,
x: <%= X %>
it is empty.
If I pass on "asd" directly as in
<some:MessageControl runat="server" X="asd" />
X gets the correct value.
What's happening here? How can I get this to work? Any suggestions are appreciated,
Nicolas
Edit: Some more context. Basically I want to be able to insert the control on a number of pages without settings its properties in the code behind, but still be able to set its visibility by calling a (varying) method from the containing page.
<%# Page Language="c#" Src="MyPage.aspx.cs" AutoEventWireup="true" Inherits="MyPage" %>
<%# Register Src="MessageControl.ascx" TagName="MessageControl" TagPrefix="some" %>
<html>
<body>
<some:MessageControl runat="server" Visible=<%# SomeBoolMethodFromContaining Page%> />
</body>
</html>
For <%= SomeMethods or Property %> expression you need to call DataBind() method in parent page or control that contains this expression on OnPageLoad event or another.
For example here code behind:
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
protected string Hello
{
get { return "hello";}
}
Here html part of the page:
<asp:Literal runat="server" Id="Literal1" Text="<%= Hello %>"/>
For Visible property use code above and <%# Method or Property%> expression. For text use <%= %> expression. It renders output as a plain text.
Hope it will help you with your question.
Best regards, Dima.
Use this:
X='<%# "asd" %>'
Note the single quotes.

How to use ASP.NET <%= tags in server control attributes?

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.

ASP.NET linkbutton visible property issue

I'm using a public variable called IsAdmin in the code behind of an aspx page.
public partial class _news : System.Web.UI.Page
{
public bool IsAdmin = false;
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.Name.Contains("admin"))
{
IsAdmin = true;
}
else
{
IsAdmin = false;
}
}
And i use the property Visible='<%#IsAdmin%>' to assign to panels which i want to show if the user is an admin in the aspx design of the page. Strangely it works for the linkbuttons i've put on the repeater.
<asp:Panel ID="Panel1" runat="server" Visible='<%#IsAdmin%>'>
<asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl='<%# "news_edit.aspx? Action=edit&id=" + Convert.ToString( Eval("news_id")) %>Edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton3" runat="server" PostBackUrl='<%# "news.aspx?Action=delete&id=" + Convert.ToString( Eval("news_id")) %>'>Delete</asp:LinkButton>
</asp:Panel>
and it works fine, however outside the repeater i've put another linkbutton without a panel
<asp:LinkButton ID="LinkButton4" runat="server" PostBackUrl="~/news_edit.aspx?action=new" Visible='<%#IsAdmin%>'>Add New Item</asp:LinkButton>
but the visible property doesn't work on it! I tried putting it inside a panel too and setting it's visible property but that too didn't work.
So i have following doubts
1)what is the issue?
2)what is the technical name when we use references like '<%#IsAdmin%>' in the design page
3)Does page load happen before page is rendered of after page is rendered?
Thanks
<%# %> is the syntax used for accessing databound fields. Since you are likely databinding the Repeater control at some point, these expressions will be evaluated.
Since you are likely not calling databind on the Panel and the Linkbuttons outside of the Repeater, these expressions will not be processed. You can probably change them to something like
<%= IsAdmin.ToString() %>
and get the result you want.
Check this great blog entry for more information on the differences.
Also, Page Load happens before the page is rendered. Rendering the page is the last thing that happens in the ASP.Net page lifecycle.

Resources