ASP User control: Cannot pass parameter from within a loop - asp.net

I can't pass a variable to an user control (ascx) from an asp page (aspx) within a loop.
I want to recursively iterate a custom control with a foreach loop (would like to avoid asp:Repeater, but if it's the only solution I'm open to suggestions about that.
I Used all the server inline tags I know, but result either gets the full
<%= stringvalue %>
to the control (meaning in the string variable which receives the parameter in the control, I see the expression and not the value) or null when I use binding tags
<%# stringvalue %>
Here's what I'm doing in the aspx file:
<%foreach (string item in listItems)
{
tempItem = item;
%>
<uc:CustomControl runat="server" id="controlId" AutoPostback="true" parameterCustom='<%# Eval("tempItem")%>'/>
<%
}%>
And in the control I have
public string parameterCustom {get;set;}
which should receive the value

Related

ASP.NET validation message "Attribute ... is not a valid attribute of element ..." for user control

We have ascx user controls written in VB.NET for an ASP.NET 4.0 project. The built-in VS page validator always displays the message from the question for all custom properties of our user control.
For instance, here is the beginning of the code of one of our controls:
<%# Control Language="VB" ClassName="PicView" %>
<%# Import Namespace="System.Drawing" %>
<script runat="server">
Public ImageUrl As String
When we try to use this control using code like this
<%# Register TagPrefix="foo" TagName="PicView" src="~/ascx/PicView.ascx" %>
<foo:PicView ImageUrl="screenshots/image.gif" runat="server" />
, the "Error List" pane displays this message:
Attribute 'ImageUrl' is not a valid attribute of element 'PicView'
The property works fine in compiled aspx pages, but how to get rid of this in the VS IDE? And enable IntelliSense for such properties if it's possible?
Got answer here:
ImageUrl needs to be a property, rather than a field, for example:
Public Property ImageUrl As String
Get
Return _imageUrl
End Get
Set(value As String)
_imageUrl = value
End Set
End Property
Private _imageUrl As String

using <%= %> or <%# %> with runat=server in ASP.NET

I have a web control that looks like this
public class Foo : WebControl
{
[Bindable(true)]
[Category("Default")]
[DefaultValue("")]
[Localizable(true)]
public string Bar { get; set; }
protected override void Render(HtmlTextWriter output)
{
output.WriteLine(Bar);
}
}
I want to put this webcontrol in my aspx page like so:
<cc1:Foo Bar="<%= Fa.La.La %>/otherstuff" runat="server" />
(obviously this code is simplified to show the problem)
In my Render method the variable Fa.La.La is not evaluated. It's coming in as the raw text "<%= Fa.La.La %>" How do I evaluate it?
I'm not particular how the variables are passed in. If the variables can be evaluated if they are passed in as <%# ... %>, that works fine. The point is I have some server-side variables I want evaluated before/while my Render() method is called.
The only thing I can think of is to use a regex to grab the contents of <%= ... %> and use reflection or something, but there has to be a more elegant way to do this.
This question is pretty similar to using server variables in a href <%= xx %> with runat=server, but it's not exactly the same since none of the answers there were useful.
Well, first you should be clear to diff between both tags.
here are some points i have read and used practically..
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.
read more it on MSDN Blog
You should have to use binding expression <%# expr %>.
<cc1:Foo Bar='<%# String.Concat(Fa.La.La,"/otherstuff")%>' runat="server" />
and call DataBind() method in code-behind.
public void page_load()
{
DataBind();
}

Is there a way to insert text into a page without "Response.Write"?

I 'm trying to make a "login information" on the top panel, like "Welcome Back XXX", so I use
<% Response.Write(Session["username"]); %>
inside the aspx page.
It works, but is there anyway to use the variable directly without Response.Write here? It seems unnecessary.
There is a simple "shortcut" in the ASP.NET page syntax to Response.Write.
<%= Session["username"] %>
is functionally equivalent to
<% Response.Write(Session["username"]); %>
Typically you want to encode your session variables as HTML using Html.Encode, in case they contain characters which are not in the accepted HTML range. If you're using ASP.NET 4, you can use <%: %>, which is equivalent to Response.Write(Html.Encode(string)).
You can do it like this:
<%= Session["username"] %>
And if you use ASP.NET 4.0 you can automatically HTML encode the value by using this syntax:
<%: Session["username"] %>
put a asp.net label on your page, like
<asp:Label id=lblUserName runat="server" />
and on your codebehind page, on page_load event or on proper event
lblUserName.Text = String.Format("welcome back {0}",Session["username"]);
use a label and assign user name to it
In aspx (html code)
<asp:Label id=lblUserName runat="server" />
In aspx.cs (Code behind)
lblUserName .Text = "Welcome back"+Session["username"].ToString();
The correct way.
First is to check if the value is null
Second because you write it on a page, use the HTMLEncode to be sure that you avoid any type of injection, or problems.
now, if you like to use a Literal or a Label, or just direct write it, is up to you. If you going to place it inside an UpdatePanel you must use a Literal.
Now, if you use Literal avoid to set the ViewState to gain space from it, ether way you need to set it on PageLoad. And it will be
<asp:Literal runat="server" id="txtUserName" EnableViewState="false" />
and on page load.
if(Session["username"] != null)
{
Debug.Assert(Session["username"].ToString.Length > 0 , "Check out why I have zero user name");
txtUserName.Text = Server.HTMLEncode(Session["username"].ToString);
}

How to access id of <asp:Hidden> control from ascx page to cs page

This is my ascx Code:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Demo.ascx.cs"
Inherits="Demo" %>
<asp:HiddenField ID="hidden" runat="server" Value="" />
And the aspx:
<%# Register TagName="Hidden" TagPrefix="CRS" Src="~/Demo.ascx" %>
<div>
<CRS:Hidden ID="hid" runat="server" />
</div>
Now How to access Hidden variable ID From ascx page to this cs page backend
Do you mean the actual ID? or the Value within the hidden field?
You can access the value using the FindControl method
HiddenField hf = (HiddenField)this.hid.FindControl("hidden");
string theValue = hf.Value;
Not sure if this is exactly what you are looking for.
Alternatively, you can declare some public properties in the UserControl in which you can access directly
In the ascx code:
public string theValue { get; set; }
In the aspx code:
string theValue = this.hid.theValue;
To access the HiddenField inside the UserControl from the asp.net web page you will need to wire up something called a Public Property.
This code should be added to the UserControl ascx.cs code behind:
public string Value
{
get { return hidden.Value; }
set { hidden.Value = value; }
}
You could then write code like this in your asp.net page:
string SomeHiddenValue = hid.Value;
hid.Value = "Its a secret!";
Note: I haven't compiled this so I am not sure if the public property name of Value will compile. I am also not sure if the second value in set { hidden.Value = value; } needs capitalising. Try changing these two values if you encounter problems.

Using codeblocks within usercontrols

I tried using a codeblock syntax within a property sent to a web user control:
<uc1:MyControl ID="MyControl1" runat="server" SomeProperty="<%= somevalue %>"/>
The user control has the public property SomeProperty declared and also uses code block to display the property value:
<p><% = SomeProperty %></p>
The output on my page is unfortunately
<p><%= somevalue %></p>
And not the actual value. Anyone know of some workaround for this?
You are trying to assign a server side value on a server side control - this is not possible.
You can use code blocks in client side code (that doesn't have a runat="server" attribute), this of course doesn't not apply to server side controls.
Set the attribute in the code behind (ascx), before OnRender:
// In onload, pre render or other event handler
MyControl1.SomeProperty = somevalue; // C#
MyControl1.SomeProperty = somevalue ' VB.NET
Try assigning the value of the property to a Label and call the .DataBind() method on the control.

Resources