adam78
adam78

Reputation: 10078

How to pass a class model/object from codebehind to aspx page?

How do I pass a class model object to my aspx page from code behind. In ASP MVC I can do it easily using a view model. Unfortunately I'm stuck with a asp webforms application that requires some enhancements and I'm not to familar with asp.net webform and repeater controls.

protected void Page_Load(object sender, EventArgs e)
{
            var orders = new List<Orders>();

             // Do some stuff and get orders

            var userInfo = new UserInfo()
            {
                Name = "Joe Blogs,
                Age = "25",
                Address = "123 Green Lane",
                Orders = orders
            };

}

I know I can create server variables and pass them individualy as follows but really I need to pass an object as it may containt an IEnumerable value that I need to iterate over in my aspx page. So I'm attempting at something like below:

<% foreach (var order in UserInfo.Orders) { %> <!-- loop through the list -->
  <div>
    <%= order %> <!-- write out the name of the site -->
  </div>
<% } %>

Any help appreciated.

Upvotes: 2

Views: 1726

Answers (1)

Andrei
Andrei

Reputation: 56716

You can have a property, or a method, which return the object, and call it on the page. Make sure to use the right markup. In data bound context use:

<%# GetUser() %>

outside of that use

<%= GetUser() %>

Few considerations:

  • Make sure that the final output of expressions inside these tags is a string.
  • GetUser or however you call it cannot be private
  • In data binding context (e.g. inside gridview, repeater or such) this method will be called when the control is data bound
  • Outside of data binding context this code will be executed really early - don't rely on fetching data from DB on Page_Load, that is too late

However I would like to mention that you may want to reconsider the whole approach here. Plain foreach iteration inside aspx is usually a bad practice. Besides it will be difficult to get this markup right. Why do that when you can have a repeater bound to your data?

<asp:Repeater ID="Repeater1" ...>
    <ItemTemplate>
        <%# Eval("OrderName") %>
    </ItemTemplate>
</asp:Repeater>

Repeater1.DataSource = userInfo.orders;
Repeater1.DataBind();

That would look much cleaner than any iteration inside aspx.

Upvotes: 4

Related Questions