Is it possible in ASP.NET to dynamically load up a WebControl from a string with some tag contents in it (without writing a bunch of custom code)?
For instance, I have a string like the following:
string controlTag = "<asp:Label ID=\"lblLabel\" runat=\"server\" />";
I then want to do something like the following to load up the control from that string:
WebControl webControl = LoadControlFromTagString(controlTag);
I can simply parse the string myself and dynamically load up a control in LoadControlFromTagString, but I was wondering if there is anything built in to .NET I can take advantage of. Any suggestions?
There are several choices, depending on what you want to do your control instance (and how much control you want over stuff like rendering, databinding, etcetera).
The easiest is probably TemplateControl.ParseControl(String) which you have access to via your current Page instance.
Related
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.
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.
My issue is that I have a designer that will create a custom aspx page bu without any .net controls. I need a way of adding the controls dynamically. So far the only types of controls will be textboxes and a button, but there are 30 variations of what the textboxes can be (name, phone #, email, etc). Also the textboxes may or may not need to be required. Once the textboxes are added the form will be submitted to a db.
My first thought was to have the designer place something like [name] and then replace that with a user control that has a name textbox and a required field validator. In order to determine if the validator should be enabled I was thinking that the place holder could look like this, [name;val] or [name;noval]. I could either do replace the place holders in code dynamically or set up a tool that the user pastes their html into a textbox and clicks a button which then spits out the necessary code to create the aspx page.
I'm sure there must be a better way to do this but its a fairly unique problem so I haven't been able to find any alternatives. Does anyone have any ideas?
Thanks,
Kirk
IF your designer gives you html pages, just create a new website. copy and pages all the HTML pages with the Image folders and everything to your project. then for every HTML page create an aspx page, (with the same name) copy and pages the html's tags which are between to the aspx page's and for the body copy and paste HTML page's tags which are between into the of the aspx page.
Now you have your aspx page, exactly the same as html page.
Sounds like an attempt to over-engineer a solution to what should be a non-issue.
As #Alessandro mentioned in a comment above, why can't the designer provide you with pages that have the control markup? As it stands right now, the designer isn't providing you with "a custom aspx" so much as "a custom html page." If the designer is promising ASPX but delivering only HTML, that's a misinterpretation somewhere in the business requirements.
However, even if the designer is rightfully providing only HTML, there shouldn't be a problem with that. At worst, you can set each element you need on the server to runat="server" to access them on the server-side. Or, probably better, would be to simply replace them with the ASPX control markup for the relevant controls.
Write a simple parser that will recognize the [...] tags and replace them with corresponding controls. Its pretty easy to do and i've often done this... the tag i use is usually $$(..); though, but that doesn't matter as long as your parser knows your tags.
Such a parser will consist of a simple state-machine that can be in two states; text-mode or tag-mode. Loop through the whole page-text, char for char. As long as you're in text-mode you keep appending each char into a temporary buffer. As soon as you get into tag-mode you create a LiteralControl with the content of the temporary buffer and add it to the bottom of your Control-tree, and emtpy the buffer.
Now, you still keep adding each char into the buffer, but when you hit text-mode again, you analyze the content of the buffer and create the correct control - could be a simple switch case statement. Add the control to the bottom of your control tree and keep looping through the rest of the chars unto you read the end and keep switching back and forth between text-mode and tag-mode adding LiteralControls and concrete controls.
Simple example of such a parser... written in notepad in 4 minutes, but you should get the idea.
foreach (var c in text)
{
buffer.Append(c);
if (c== '[' && mode == Text)
{
mode = Tag;
Controls.Add(new LiteralControl(buffer));
buffer.Clear();
}
if (c == ']' && mode == Tag)
{
mode = Text;
switch (buffer)
{
case "[name]": Controls.Add(new NameControl());
... the rest of possible tags
}
buffer.Clear();
}
I'm wondering if anyone has any experience converting User controls to Web controls?
Ideally, I'd like to offload some of the design work to others, who would give me nicely laid out User Controls. Then, I could go through the process of converting, compiling, testing and deploying.
Until MS comes up with the magic "Convert to Server Control" option, it looks like I'm pretty well stuck with re-writing from scratch. Any ideas?
Is there a reason you must convert these user controls to server controls? Remember that it is possible to compile a user control into an assembly.
You are right there is no magic bullet here but since you already have a User Control its not that difficult.
Make sure all properties, events, etc. are set in the code behind since you won't have any mark up when you're done
Create a new Server Control
Paste all of the event handling and property setting code into the new control
override the Render method for each child control call the RenderControl Method passing in the supplied HtmlTextWriter
protected override void Render(HtmlTextWriter writer)
{
TextBox box = new TextBox();
//Set all the properties here
box.RenderControl(writer);
base.Render(writer);
}
I searched for hours and found many blogs about it.
The only thing worked for me was this article https://blogs.msdn.microsoft.com/davidebb/2005/10/31/turning-an-ascx-user-control-into-a-redistributable-custom-control/.
It says self-contained with given restrictions, but it does not mentions that the codebehind must be included in ascx file.
I used a Web Site project (not Web application!) and had to inline the code behind into the ascx file and only use control directive like:
<%# Control Language="C#" ClassName="MyPackage.MyControl"%>
So basically i just have a single file left for the user control. When codebehind was a separate file all control's where null when i referenced the final dll.
I also tried http://blog.janjonas.net/2012-04-06/asp_net-howto-user-control-library-compile-dll-file but with reflection the ascx file could not be found.
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.