Using codeblocks within usercontrols - asp.net

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.

Related

Reference to querystring parameters in .aspx markup code

I'm trying to reference a query string parameter inside an HyperLink element :
<asp:HyperLink runat="server" NavigateUrl='<%# Eval(Request["id"], "~/PATH/Page.aspx?id={0}") %>' Text="reload" />
I tought it was simple... but it's not: NavigateUrl property probably fails evaluation an the resulting url is empty.
Of course Request["id"] is valid at the time the page is evaluated.
I tried also using string.format() instead Eval() with the same result.
This means <%# ... %> data-binding expression
The data-binding expression creates binding between a server control property and a data source when the control's DataBind method of this server control is called on the page.
But you are only formatting a string to set for your NavigateUrl
Inline code block is not allowed to any server tag controls
those that have runat="server"
You can only set it via code either eg: inside the Page_Load
protected void Page_Load(object sender, EventArgs e)
{
HyperLink1.NavigateUrl = string.Format("~/PATH/Page.aspx?id={0}", Request["id"]);
}
Your second post work's because it's a pure html client control and not a server control.
Source: Inline Expressions
I didn't fully understand what the problem was but the following code works:
<a href="~/PATH/Page.aspx?id=<%= Request.QueryString["id"].ToString() %>" >reload</a>
I tried several times including one using <a></a> tag with runat="server" property (not working).

Validation based on visibility of a label

I like to add a validation on a label based on its visibility, in that a submit button will raise a validation message or error if the label is not visible.
I am used to the validation controls in the Toolbox, which wont allow this functionality!
It seems as though if an asp:Label's visibility is set to false, the asp.net engine will not even put it in the DOM. So you can check in javascript, using the onclick property of the (html) button to check if the label is in the DOM or not, and use asp.net's __doPostBack() javascript function to post back to the server if it is there:
<script type="text/javascript">
function testMe()
{
var lbl = document.getElementById('lblTest');
if(lbl == null)
document.getElementById('msg').innerHTML = "Error";
else
__doPostBack('testButton');
}
</script>
<asp:Label ID="lblTest" runat="server" Visible="false" Text="Hello"></asp:Label>
<button onclick="testMe();">test</button>
To be completely honest, I thought the lbl would be undefined if the label did not exist in the DOM, but Firebug revealed it is actually null. Anyway, a couple things to note is that in order for asp.net to define the __doPostBack() method, I believe you need some control in the form that has autopostback="true", and in the code-behind you can check what caused the postback in the Page_Load method like so:
if(Request.Form["__EVENTTARGET"] == "testButton") {}

How to set focus to a web control in ASP.NET

Question: What is the best way to set focus to a web control in ASP .NET.
I can do it, but it's ugly. I have a web control wrapped in a web control hosted on a web page. So, if you do a view | source on the page the id is something like WrapperControl_Control_TextBox.
I've tried the "tried and true" Javascript methods of grabbing the element and setting it's focus: document.getElementByID( "WrapperControl_Control_TextBox" ).focus(); and it didn't work. I'm not sure why.
I know I could possibly do:
document.getElementById( "<%= TextBox.ClientID %>" ).focus(); too, I think. This won't work because of another totally separate error based on the fact you can't dynamically add controls to a header if there is a "<% %>" in the page. GAH.
In the "bottom-most" control, I've tried setting the focus (TextBox.Focus() in Page_Load) and that doesn't work either.
Anyway, the way that works is by simply taking the ControlsCollection of the Page, grabbing the control I need from that, getting it's collection, grabbing the next lower control and so forth.
I only have to do this seven times. So I have eight foreach loops.
Basically, my code is like this:
///////////////////////////////
// On the page
///////////////////////////////
ControlCollection controls = Controls;
foreach( Control control in controls)
{
if ( string.Equals( control.ID, "FormID", StringComparison.InvariantCultureIgnore ) )
{
ControlCollection nextControls = control.Controls;
foreach( Control nextControl in nextControls )
{
if ( string.Equals( nextControl.ID, "DivICareAboutInTheForm", StringComparison.InvariantCultureIgnor ) )
{
ControlCollection nextNextControls = nextControl.Controls;
//:
//:
//Yes, it's that bad and so forth.
//:
//:
}
}
}
}
You can use jQuery to do a search for IDs that end with your textbox name. This way you wont have to call the UniqueID server-side code. Just make sure not to have multiple controls that end with the same name
<script type="text/javascript">
$(document).ready(function() {
$('[id$=txtBox]').focus();
});
</script>
Or, you can use a Class name for the default text box.
<asp:Textbox ID="txtBox" runat="server" cCssClass="defaultTextbox" />
jquery:
$('.defaultTextbox').focus();
You can get around the "cannot add dynamic controls because a <%= %> block exists on the page" error by changing the block to use databinding syntax: <%# TextBox.ClientID %>, and manually calling Page.DataBind() in Page_Load.
If you really want to use the Page_Load method, then you could always call the SetFocus method on the Page object.
Page.SetFocus(myTextBox);

Inline Data-Binding asp.net tags not executing

My problem is I used to be able to do this,
< div runat="server" visible='<%#CallAFunctionThatReturnsBoolean() %>' >
and CallAFunctionThatReturnsBoolean() will be called in Page_Load when the control's DataBind function gets called implicitly and the div's visibility will be set correctly.
Now for some reason this doesn't happen anymore, and to make it work I would have to either call Page.DataBind() in my base Page class or Me.DataBind() in the Page_Load sub in that page, but I don't really want to do this, especially in the base Page class because then if I have a page with let's say a DataGrid in it that I already call the DataBind() function explicitly, then this DataGrid will get bound twice, once from Page.DateBind and once from the explicit call datagrid.DataBind().
Any idea why the control's data binding event is not called implicitly anymore?
Thanks
The <%# happens for databinding, the <%= will happen always when the page is being built reglardless of any databinding. It sounds like that is what you are looking for?
Also databinding is control level so if you 'DataBind' a grid, it will not databind any other controls. Even embedded templated controls will not be automatically databound when the grid is called unless you wire the up to do so.
Try doing the following and see if it corrects your problem:
<div runat="server" visible='<%= CallAFunctionThatReturnsBoolean() ? "true" : "false" %>' >
If you require it to occur in the databinding event, I prefer to implement OnDataBinding server side as follows:
// in your aspx
<div runat="server" OnDataBinding="yourDiv_DataBinding">
// in your .cs
protected void yourDiv_DataBinding(object sender, EventArgs e)
{
HtmlControl div = (HtmlControl)(sender);
div.Visible = CallAFunctionThatReturnsBoolean();
}

Access an asp:hiddenfield control in JavaScript

What is the best way to access an ASP.NET HiddenField control that is embedded in an ASP.NET PlaceHolder control through JavaScript? The Visible attribute is set to false in the initial page load and can changed via an AJAX callback.
Here is my current source code:
<script language="javascript" type="text/javascript">
function AccessMyHiddenField()
{
var HiddenValue = document.getElementById("<%= MyHiddenField.ClientID %>").value;
//do my thing thing.....
}
</script>
<asp:PlaceHolder ID="MyPlaceHolder" runat="server" Visible="false">
<asp:HiddenField ID="MyHiddenField" runat="server" />
</asp:PlaceHolder>
EDIT: How do I set the style for a div tag in the ascx code behind in C#? This is the description from the code behind: CssStyleCollection HtmlControl.Style
UPDATE: I replaced the asp:hiddenfield with an asp:label and I am getting an "undefined" when I display the HiddenValue variable in a alert box. How would I resolve this.
UPDATE 2: I went ahead and refactored the code, I replaced the hidden field control with a text box control and set the style to "display: none;". I also removed the JavaScript function (it was used by a CustomValidator control) and replaced it with a RequiredFieldValidator control.
My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response.
My suggestion to solve your problem is
Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css.
If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :
placeholderId.Attributes["style"] = "display:none";
Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.
If the Visibility is set to false server-side, the placeholder won't be rendered and you won't be able to access anything inside it from JavaScript. Your code should work when the placeholder is visible="true"
Get rid of the placeholder, leave the hidden field empty at first, after the search populate it.
Try this:
function popup(lid)
{
var linkid=lid.id.toString();
var lengthid=linkid.length-25;
var idh=linkid.substring(0,parseInt(lengthid));
var hid=idh+"hiddenfield1";
var gv = document.getElementById("<%=GridViewComplaints.ClientID %>");
var gvRowCount = gv.rows.length;
var rwIndex = 1;
var username=gv.rows[rwIndex].cells[1].childNodes[1].innerHTML;
var prdid=gv.rows[rwIndex].cells[3].childNodes[1].innerHTML;
var msg=document.getElementById(hid.toString()).value;
alert(msg);
document.getElementById('<%= Labelcmpnme.ClientID %>').innerHTML=username;
document.getElementById('<%= Labelprdid.ClientID %>').innerHTML=prdid;
document.getElementById('<%= TextBoxviewmessage.ClientID %>').value=msg;
return false;
}
<ItemTemplate>
<asp:LinkButton ID="LabelComplaintdisplayitem" runat ="server" Text='<%#Eval("ComplaintDisp").ToString().Length>5?Eval("ComplaintDisp").ToString().Substring(0,5)+"....":Eval("ComplaintDisp") %>' CommandName ="viewmessage" CommandArgument ='<%#Eval("username")+";"+Eval("productId")+";"+Eval("ComplaintDisp") %>' class='basic' OnClientClick =" return popup(this)"></asp:LinkButton>
<asp:HiddenField ID="hiddenfield1" runat ="server" Value='<%#Eval("ComplaintDisp")%>'/>
</ItemTemplate>
If the place holder visibility is set to false, it will never be rendered , and the hidden field value will be only stored in the ViewState of the page.
just one question, why are you setting the visibility of the place holder to be false , if its containing a hidden field?
Anyway one possible way to get over this issue, is adding a TextBox or Label object , and set the display CSS style of it to "none" , then in your code copy whatever you are putting in the hidden field into the textbox/lable text property, this way you can easily read the value using javascript , since the textbox/label will be rendered but not visible to others, though this might not be that safe thing to do.
Instead of making ".visible=false", change the style to "display: none;". That will render your control but make it invisible.
Visible doesn't actually make it visible, you can leave it default. Just runat="server" and use its .Value.

Resources