4

Is it possible to have a method that return a string with ASP.NET code get called in an aspx file and have that code run before the page is reloaded?

So pretty much have something like the following:

<asp:DataList //blahblah>
   <ItemTemplate>
      <%= GenerateTable() %>
   </ItemTemplate>
</asp:DataList>

GenerateTable() creates a table with asp:Label objects in them whose values are determined by the DataSource of the asp:DataList.

Right now, I have the ASP.NET code generating properly. The problem is that it's not translated into HTML before the page loads so you can't see it.

Update: The reason why I want a separate method for generating the ASP.NET code is because I want to make the columns displayed configurable, so the same columns are not always displayed by the website.

Update for Solution Attempt: I tried creating the following User Control to insert my ASP.NET code, but it's still running into the same problem. Am I doing this wrong?

User Control:

 <%@ Control Language="C#" CodeBehind="TableGenerator.ascx.cs"      Inherits="DagReport_WebRole.DynamicData.FieldTemplates.TableGenerator" %>

<div class="tableRow">
    <%= this.GetASPCode() %>
</div>

User Control C#: using System.Web.UI;

namespace DagReport_WebRole.DynamicData.FieldTemplates
{
    public partial class TableGenerator : System.Web.DynamicData.FieldTemplateUserControl
    {
        public string Code { get; set; }

        public string GetASPCode()
        {
             return Code;
        }
    }   
}

In My ASPX File:

            <ItemTemplate>
                <div class="dagRow"></div>
                <userControl:TableGenerator
                    Code="<%=GetRowASPCode()%>"></userControl:TableGenerator>
            </ItemTemplate>
2
  • How about using abstract classes and decorators (pattern) to inject different objects dynamically? This can be done using dependency injection for example. Commented Aug 16, 2013 at 22:40
  • @PmanAce I'm not sure I understand. Can you give me an example of that? Commented Aug 16, 2013 at 22:42

3 Answers 3

10

Instead of direct code injection like you're trying now, you can add a user control into your ItemTemplate and execute your code in the user control. The code would dynamically build needed ASP.NET controls and add them to user control's .Controls collection.

This way you will have the best of both worlds: your dynamic code execution and (since user control participates in page lifecycle) proper HTML generation.

UPDATE

Here is a basic example. Let's say you created user control "WebUserControl2.ascx" and added it to your main page:

<%@ Register src="WebUserControl2.ascx" tagname="WebUserControl2" tagprefix="uc1" %>

Then you can add it to your DataList ItemTemplate:

 <asp:DataList runat="server" ID="DataList1">
 <ItemTemplate>
     <uc1:WebUserControl2 ID="MyWebUserControl" runat="server" />                
  </ItemTemplate>
 </asp:DataList>

And in your code for web user control WebUserControl2.ascx.cs you add a label, a textbox and a button:

protected void Page_Load(object sender, EventArgs e)
{
    Label Label1 = new Label();

    Label1.ID="Label1";
    Label1.Text = "Please enter info: ";
    this.Controls.Add(Label1);

    TextBox Textbox1 = new TextBox();
    Textbox1.ID="Textbox1";
    this.Controls.Add(Textbox1);


    Button Button1 = new Button();
    Button1.ID = "Button1";
    Button1.Text = "Submit";
    this.Controls.Add(Button1);

}

When the page runs and DataList is bound, you will get something like:

enter image description here

You can add properties to the user control and assign their values from the main page, for example DataList ItemCreated event, this way the control will be aware which item is currently being created and act accordingly.

Sign up to request clarification or add additional context in comments.

9 Comments

thanks! I'll look into this! if you have any good references, please let me know. =]
I think I'm still running into the same problem where the ASP code gets generated but not executed. I'll add my code above.
You're still using <%= %>. Don't. Execute whatever code you need inside of Control's CS code itself, e.g. in Load event. Don't send that code as control output. And inside of that inner CS code generate whatever controls you need adding them to control's collection.
what if I need HTML code to surround the controls? They're all just asp:Labels in a table so there are surrounding tds and trs which also specify the widths of the columns.
you can build entire structure, table, labels and anything else you need dynamically. You can add Table to usercontrol .Controls collection and fill it with rows and cells by adding them to the Table. You can add labels etc, to table Cells dynamically as well.
|
3

No, because the code GenerateTable() will not be run until data-binding of the DataList occurs which is during Page_Load or later, depending upon if you have an event handler doing the data-binding instead of a built-in page event.

UPDATE:

To load data outside of the page life cycle, then you need to do it outside the page life cycle.

To inject HTML into the page in between page updates, then you will need to invoke an AJAX call on the client-side, like this:

Here we have a click handler that loads an HTML snippet from the server, but it could easily be adapted to return dynamic HTML through server-side logic or templating.

<script type="text/javascript">
    $(document).ready(function () {
        $("#myButton").click(function() {
            $.get("YourFile.html", function(data) {
                $("#YourDIV").append(data);
            });
        });
    });
</script>

NOTE: Be aware that a page load will wipe away this dynamically loaded data though.

3 Comments

Aww, man. Thanks! Do you know if there's a way to work around that?
Is there a way to insert the code there before the data-bind? I do call it from event handlers.
If you really want to have HTML injected into the page, then your best bet is to do through an AJAX call on the client-side, see UPDATE in answer.
0

Not sure exactly what you are trying to accomplish but how about nested repeaters:

<asp:Repeater ID="repeaterConversation" runat="server">
    <ItemTemplate>
        <asp:Repeater ID="rptPosts" runat="server">
            <ItemTemplate>
            </ItemTemplate>
        </asp:Repeater>
    </ItemTemplate>
</asp:Repeater>

Then in your code-behind:

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    repeaterConversation.DataSource = source
    repeaterConversation.DataBind()
End Sub

Protected Sub repeaterConversation_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles repeaterConversation.ItemDataBound
    If (item.ItemType = ListItemType.Item Or item.ItemType = ListItemType.AlternatingItem) Then
        //here you can do calulations based on the data bound in the parent repeater
        //and also bind to controls and child repeaters
        Repeater_Posts = item.FindControl("rptPosts")
        Repeater_NewPostBtn = item.FindControl("btnNewPost")
        Repeater_Posts.DataSource = source
        Repeater_Posts.DataBind()
    End If
End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.