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?
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?
Please post some more of your code?
A couple of things:
productId
is an object reference (to a string
object) which means:
unless you write some intialisation code to 'fill' it with a string reference at the start, it will be null
.
if you create a string e.g. string x = new String()
x will be an empty string, which you can think of as "" without the quotes. (It is a string, but its empty because it has no characters in it).
you can just write return productId;
- no need to call ToString()
on a string.
ViewState
or hidden form fields to do this.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With