Reputation: 10078
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
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:
GetUser
or however you call it cannot be privateHowever 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