Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign complex object to user control in markup

I can do this in code-behind, but I'm looking for a lazy way of doing this in the markup itself:

Suppose I have a UserControl with a complex property:

public class MyControl : UserControl {
    public Person Someone { get; set; }
}

And I have a page with this control:

<uc1:MyControl id="my1" runat="server" />

I want to put a person into this control from the page markup, not the code-behind. In code-behind, it would look something like:

my1.Someone = GetSomePerson();

I'd like to do:

<uc1:MyControl id="my1" runat="server" Someone="<%= GetSomePerson() %>" />

but that's not valid. Any suggestions on how to do this? I think I can do it one property at a time, but I'm looking for a more generic approach - the complex object I'm passing in is much bigger than this example (dozens of properties), so I don't want to define them all individually in the markup even if I could.

I'm wondering if there's some kind of magic <%$ %> function that will do this.

like image 420
Joe Enos Avatar asked Sep 06 '25 17:09

Joe Enos


2 Answers

I found someone who implemented exactly what I was looking for:

http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx

After including some code and a new expression builder in web.config, you can do this by using an ASP.NET expression:

<uc1:MyControl runat="server" Someone="<%$ Code:GetSomePerson() %>" />

I don't think I'll do it in my current project, since it's not really a standard. I'm sure people would be totally bad-mouth me down the road when they're looking at the code and trying to figure out what I did - but it's definitely good to know for the future.

EDIT

For posterity, just in case this link doesn't work forever, here's the relevant code:

// C#:
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder {
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, 
       object parsedData, ExpressionBuilderContext context) {
        return new CodeSnippetExpression(entry.Expression);
    }
}

// Web.config:
<compilation debug="true">
  <expressionBuilders>
    <add expressionPrefix="Code" type="Infinity.Web.Compilation.CodeExpressionBuilder"/>
  </expressionBuilders>
</compilation>

// ASP.NET .aspx:
<asp:CheckBox id="chk1" runat="server" Text="<%$ Code: DateTime.Now %>" />
like image 163
Joe Enos Avatar answered Sep 08 '25 10:09

Joe Enos


<uc1:MyControl id="my1" runat="server" />
<% my1.Someone = GetSomePerson(); %>

or since this clearly wasn't the answer you were looking for...

<uc1:MyControl id="my1" runat="server" someParameter="uniqueId" />

And then inside the uc1 control

public string someParameter;
Someone = GetSomePerson(someParameter);
like image 42
Brad M Avatar answered Sep 08 '25 11:09

Brad M