将参数传递给用户控件 - asp.net

Cri*_*riu 6 c# asp.net

我有这个用户控件:

<user:RatingStars runat="server" product="<%= getProductId() %>" category="<%= getCategoryId() %>"></user:RatingStars>
Run Code Online (Sandbox Code Playgroud)

您可以通过调用两种方法来查看我填写产品和类别:

public string getProductId()
{
    return productId.ToString();
}

public string getCategoryId()
{
    return categoryId.ToString();
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么在用户控件中,当我接收到的数据(产品和类别)时,它给了我"<%= getProductId()%>"而不是给出从该方法收到的id ...

任何帮助将不胜感激......

编辑:解决方法:product ='<%#getProductId()%>'

最后一个问题:在用户控件中我有这个:

 public string productId;
 public string product
{
    get
    {
        return productId;
    }
    set
    {
        productId = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,我希望在用户控件中将productId设置为ok.不幸的是,当我尝试使用它时它是空的...

有什么我写的不正确吗?

Tow*_*own 8

因此,您可以获得编译时检查,您可以为您的用户控制ID,然后在C#中设置它Product和Category属性,如下所示:

ASPX:

<user:RatingStars id="myUserControlID" runat="server" Product="<%= getProductId() %>" Category="<%= getCategoryId() %>"></user:RatingStars>
Run Code Online (Sandbox Code Playgroud)

CS:

myUserControlID.Product = GetProductId();
myUserControlID.Category = GetCategoryId();
Run Code Online (Sandbox Code Playgroud)

此外,正如5arx提到的,一旦你填充了那么刷新你的页面将重新加载你的控件,你将丢失Product和CategoryID.您可以通过在用户控件的属性上使用ViewState来处理它,如下所示:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:我已经更新了属性名称大小以遵循惯例,因为它对我来说更有意义!就个人而言,我总是使用ID(例如:)后缀ID ProductID来区分它与包含Product对象的属性.在此处阅读有关编码标准的更多信息:是否有任何关于开发C#编码标准/最佳实践文档的建议?