Pass parameters to a user control - asp.net
asp.net, c#
Solution
So that you get compile-time checking, you can give your user control an `ID` and then set its `Product` and `Category` properties in C# like this:
ASPX:
<user:RatingStars id="myUserControlID" runat="server" Product="<%= getProductId() %>" Category="<%= getCategoryId() %>"></user:RatingStars>
CS:
myUserControlID.Product = GetProductId();
myUserControlID.Category = GetCategoryId();
Also, as 5arx mentions, once you've populated that then refreshing your page will reload your control and you'll lose the `Product` and `Category` IDs. You can handle that by using ViewState on the properties in your user control, like this:
private const string ProductKey = "ProductViewStateKey";
public string Product
{
get
{
if (ViewState[ProductKey] == null)
{
// do whatever you want here in case it's null
// throw an error, return string.empty or whatever
}
return ViewState[ProductKey].ToString();
}
set
{
ViewState[ProductKey] = value;
}
}
NOTE: I've updated the property name casing to follow convention, as it just makes more sense to me that way! Personally, I'd always suffix IDs with `ID` (eg: `ProductID`) to distinguish it from a property that contains a `Product` object. Read more about coding standards here: Are there any suggestions for developing a C# coding standards / best practices document?
Problem
I have this user control: ``` <user:RatingStars runat="server" product="<%= getProductId() %>" category="<%= getCategoryId() %>"></user:RatingStars> ``` You can see that I fill in the product and category by calling two methods: ``` public string getProductId() { return productId.ToString(); } public string getCategoryId() { return categoryId.ToString(); } ``` I do not understand why, in the user control, when I take the data received (product and category) it gives me "<%= getProductId() %>" instead of giving the id received from that method... Any help would be kindly appreciated... Edit: Solved with: product='<%# getProductId() %>' Last problem: in the user control I have this: ``` public string productId; public string product { get { return productId; } set { productId = value; } } ``` So, I expect that the productId is set up ok in the user control. Unfortunately it is null when I try to use it... Is there anything I wrote that's incorrect?