When are ASP.NET Expression Builders most useful? - c#

I saw an example of using Expression Builders, and creating your own Custom Expression Builder Classes here:
https://web.archive.org/web/20210513211719/http://aspnet.4guysfromrolla.com/articles/022509-1.aspx
However, I fail to see the value in using this approach. It doesn't seem much easier than programmatically setting values in your code behind.
As far as I can tell, the only thing you can do with them is set properties. Maybe they would be useful for setting defaults on certain controls?
Can anyone shed light on where this ASP.NET feature becomes powerful?

We are using a custom expression builder to localize our application. E.g. the markup looks like this:
<asp:LinkButton Text="<%$ Str:SomeString %>" ... />
The expression builder reads a string with the ID SomeString from a resource file (taking into account the current user's language preferences) and assigns it to the Text property of the LinkButton.
This is quite flexible: we can add languages by simply copying a resource file into the application directory. And if a customer wants to have a different text for that linkbutton, he just adds his custom string to the resource files and changes the string-ID in the expression builder (without having to change the code-behind).

Custom Expressions are handy if you care about ViewState (you should). See TRULY Understanding ViewState.

It is useful when you need the expression to execute early in the page life cycle. It executes when the parameter is needed not at a particular point in the page life cycle.
Also have a look at making a general purpose 'Code' expression builder.

Making some client side javascript parameters "dynamic", is a good use for this feature.
So say you have a setting in a web.config file that you want to make its way down to a client in a javascript tag. You could handle the OnRender event in code behind and muck around with the js there but that would be ugly. Much nicer to do something like this in the ASPX:
<script type="text/javascript">
var sessionKill = <%$ AppSettings:ClientSessionTimeOut%>

Related

Adding ASP.NET User Controls at runtime via <script runat="server">

I am having trouble executing a control inside the <script runat="server"> tags in an *.aspx page.
The control works when it is defined declaratively in the HTML section of the page, but I am unable to make it work when placed within the script tag itself.
At the beginning of the page I register my control with:
<%# Register assembly="App_Web_exemple.ascx.cc671b29" namespace="Moncontrol" tagprefix="moncontrol" %>
Then, in the HTML, I call it (successfully) with the following declaration:
<moncontrol:exemple ISBN="9782894646151" runat="server" />
When I try to add it programmatically within the <script runat="server">, however, I am unable to execute it. I tried with the tags <asp:Text /> and <asp:Literal />, as follows, but that also doesn't doesn’t work.
In the HTML part:
<asp:Text id="TestControl" runat="server" />
In the script part
TestControl.Text = "<moncontrol:exemple ISBN=\"9782894646151\" runat=\"server\" />";
To clarify, what you're looking to do is programmatically add a User Control to your Web Forms page at runtime. There are a few ways of accomplishing this.
Before we begin, it's worth noting that the code you wrote likely "works" insomuch that it compiles and doesn't throw a runtime error. But it's also not executing the control. I suspect if you look at your HTML, you'll find the control declaration being output as a string literal (i.e., unprocessed by the server). It is then disregarded by the browser since it doesn't know what the <moncontrol:exemple /> tag represents. That's obviously not what you want.
Establishing a Control Container
Regardless of which approach you take, you'll want to start with some type of container on your page that you can add the control to, such as a Panel. If you don't want the container to output any wrapper markup, you can use a Placeholder:
<asp:Placeholder id="ControlContainer" runat="server" />
This serves a similar purpose as your current Text control, except its only purpose is to provide a container that you will add your user control to. From ASP.NET's perspective, however, this can be any type of server control, including a <script runat="server">, as per your request. More on that later.
Programmatically Creating the Control
Next, you're going to create the control programmatically. This is where we run into various options. The most universal approach is to use ParseControl() method (reference). This looks something like this:
Control control = Page.ParseControl("<%# Register assembly=\"App_Web_exemple.ascx.cc671b29\" namespace=\"Moncontrol\" tagprefix=\"moncontrol\" %><moncontrol:exemple ISBN=\"9782894646151\" runat=\"server\" />");
That will parse the control using the same method that processes the declarative syntax on the page, and return a Control object with your Exemple control as the first control in its Controls collection.
I find that syntax a bit sloppy, however, since it's representing a .NET object and its properties as a string literal. Given that, there are some cleaner approaches. In this case, it appears that your control is being compiled into an assembly and, therefore, likely has a Code Behind defined which inherits from UserControl. If so, you should be able to simply do something like:
Exemple control = new Exemple();
And then set the properties on it programmatically, the way you would in any other C# object. Much cleaner!
If your control was instead being compiled dynamically by the server, then you'd instead use the Reference directive with the LoadControl() method, as described in the MSDN article How to: Create Instances of ASP.NET User Controls Programmatically. I don't believe that method will work for you, however.
Adding the Control Instance to the Page
Regardless of which approach you take, the next step is the same: you then add the control you've programmatically added to your page by adding it to the Controls collection of the target container. E.g.,:
ControlContainer.Controls.Add(control);
Note: You can technically just add this to the Page class's Control collection, too, but that doesn't give you any control over where on the page it is placed; having a PlaceHolder control (or equivalent) lets you specify exactly where you want the control to appear.
I hope this helps. There are a couple of caveats depending on how you wrote and compiled your control, but this should give you the basic structure needed to address your problem.

How to get Label inner text from Codebehind

I have html label contol without runat="server"
Does it possible to get inner text from code behind c#?
Label:
<label id="lblClanName">Text Here</label>
Thanks
Every time an ASP.Net page is posted back to the server it is recreated from scratch using the custom code contained in the page (such as calls to a database), the HTTP post/get collections (which include ViewState), any custom data in Application, Cache, Session, static objects, etc.
If the value does not exist in any of those locations, the server doesn't have access to it. A common trick to pass data from the client is to simply use a hidden field. If you want something more elegant, you can use asynchronous AJAX to send/receive data from the server.
Or in this case, you could just add runat="server" to an asp:Label. ViewState will maintain the value between postbacks, though it will not reflect changes made client-side unless (once again) the data is somehow passed back to the server.
Note that ViewState is typically a bad thing because it essentially doubles the size of your data (or more) and (in my opinion) encourages sloppy design.
i don't think you can do it.either you can use js get the lable,and call js method from code behind
Short answer: no.
To access this from your code-behind, you will minimally need to add runat="server" to your label. This will allow you to access it using Page.FindControl(String).
The preferred approach, if you are able to modify the front-end code, would be to use an <asp:Label />. This will allow you easy access by just using the control's ID in the code-behind, specifically its Text property.
Do you want to know how to parse a string value for the inner html, or do you expect your web page do have text written to the label at runtime?
string labelHtml = "<label id="lblClanName">Text Here</label>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(labelHtml);
string innerText = doc.DocumentElement.InnerText;
Why do you need the text between a label, is this for a live web page? This sound like a bad design more than a requirement.

Setting meta:resourcekey on page load

I have a label on a page which gets localized text through the meta:resourcekey attribute. The issue I have is that I want it to display different text depending on which view of a multiview they're on.
I tried adding the attribute though label.Attributes.Add("meta:resourcekey", "label"), but that doesn't seem to load any text. I tried it on PreRender, and same deal. The attribute appears when I look at the source, but no text is displayed.
Is this possible to do? The other option is to have 2 labels and change the visibility on page load, but that seems like the less elegant solution.
Thanks.
I think what you want for programmatic localisation in code behind is as simple as this:
ctrl.Text = (string)GetLocalResourceObject(“myCtrlKey.Text”);
ctrl.AnotherAttribute = (string)GetLocalResourceObject(“myCtrlKey.AnotherAttribute”);
Using LocalResource means that for a page called MyPage.aspx, you have created a resource file called MyPage.aspx.resx and/or MyPage.aspx.{culturename}.resx in the special directory App_LocalResource.
If you like Global Resources instead of local, use the special directory App_GlobalResource
to hold a resource file called MyResourceFileName.resx and call:
ctrl.Text= (string)GetGlobalResourceObject(“MyResourceFileName”, “myGlobalKey”);
copied from a blog about localization in the code behind
--
PS the reason that Attributes.Add("meta:resourcekey", "label") doesn't work is that "meta:resourcekey" isn't a real attribute and its use in the aspx is not really valid aspx markup - rather it's a preprocessing directive that causes the compiler to turn it into a longer list of attributes name/value pairs, based on what you've put in your resource file.
The approach of trying to assign a meta:resourcekey attribute will not work simply because they are treated specially by the page parser, and replaced before the page lifecycle code even really begins.
But meta:resourcekey is basically a declarative replacement for the code equivalent of accessing local resource files. In other words:
<asp:Label ID="MyLabel" meta:resource-key="MyResourceKey" />
is equivalent to:
<asp:Label ID="MyLabel" Text="<%$ Resources: myResXFile, MyResourceKey %>" />
is equivalent to the code:
MyLabel.Text = Resources.MyResXFile.MyResourceKey;
It looks like you're already dealing with your label in the code if you're trying to assign attributes to it. Why not set it's value in the code?

Server-side Javascript (aspx.cs) Attributes.Add Code to Change a Label's text

I am trying to change a label's text by using server-side JavaScript (onclick) and C# within the page_load event. For example, I would like to write something like the following:
Label1.Attributes.Add("onclick", "Label2.text='new caption'")
Does anyone know the correct code for this? Also, what is this type of code referred to; is it just JavaScript or JavaScript in C# or is there a specific name? Lastly, does a book or online resource exist that lists the choices of control.attributes.add("event", "syntax") code to use with C#?
There is no server-side Javascript (unless you change to a platform other than ASP.NET where you actually use Javascript as server language). What you are doing is adding an attribute to the html tag, and the code will be executed entirely on the client side.
First, let's look at how it's done in HTML without the server side code and server side controls:
<span onclick="document.getElementById('Label2').innerHTML='Thank you';">Click me</span>
<span id="Label2"></span>
To use Label controls instead, setting the onclick attribute from server side code, you would do like this:
Label1.Attributes.Add("onclick", "document.getElementById('Label2').innerHTML='Thank you';");
This will work as long as the controls are not inside a naming container. If they are, the id of the controls are prepended with the name of the container to keep them unique, so you need to use the ClientID property to find out what their final id is:
Label1.Attributes.Add("onclick", "document.getElementById('" + Label2.ClientID + "').innerHTML='Thank you';");
The ClientID always contains the id that you can use to access the element from Javascript, so the last code always works regardless if the control is in a naming container or not.
To find out what attributes you can use, you should look at the HTML documentation, for example the Internet Explorer documentation for the span element. When looking at the documetation for a specific feature, notice the Standards Information, as that will tell you if it works in any browser or just in Internet Explorer.
The code above adds JavaScript to a server control rendered on the client. Take a look at this MSDN article - Using JavaScript Along with ASP.NET for more information.
IIRC, you will need to reference Label2 by its ClientID and will need to write some JavaScript to change the label's text value (I think ASP.NET labels get rendered as <span> tags).

Building Dynamic UI with C#?

I need to expose some input fields based on what properties I find for particular types in an assembly.
I'm not sure how common an approach like that is. Perhaps there are easier ways. Maybe on the client side instead of server.
If anyone knows of a good way of doing something like this, I would appreciate the help.
Create input controls accordingly and simple add control to some div container? I'm not sure if it would be more complex than that.
I'll need to somehow add css classes to the controls as I build them so they get placed nicely; that might get tricky.
This all sounds like standard asp.net development. Any good tutorial should be able to help you. For the asp server controls, you use the CssClass property to set the class for the control.
Here is the asp.net tutorial from the W3C Schools.
I assume you will use reflection to figure out what properties entity has, then you would based on the type of the property create an input field. You would have to dynamically create control to handle input in code behind. Make sure you give that control and id. You will have to recreate these controls on the post back. This looks to me like dynamic property editor. There might be some free ones, google for it.
If the UI doesn't have to be completely dynamic you could include all the controls in the markup with any optional ones set to Visible="false". Then, selectively enable the appropriate controls in your code-behind. For example:
Default.aspx
<asp:Button ID="EvenButton" runat="server" Text="Even" Visible="false" />
<asp:Button ID="OddButton" runat="server" Text="Odd" Visible="false" />
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
String msg = "A message to count";
if (msg.Length % 2 == 0)
{
// Enable the Even Button
EvenButton.Visible = true;
}
else
{
OddButton.Visible = true;
}
}
The advantage of this method is that you can lay things out with the appropriate CSS easily in the markup. If, on the other hand, your UI is much more dynamic than this, you'll probably have to resort to dynamically creating controls in the code-behind and adding them to the page via calls to Controls.Add(). This way, however, is harder to layout. And you have to deal with things like re-wiring any event handlers on each postback.
Hope that helps.
I ended up leveraging jQuery.
I laid out a simple markup with the basic layout I would need.
For creating controls dynamically, I did it all in javascript using jQuery methods.
This of course requires that you return some data set to the UI intelligently enough to render it.

Categories

Resources