Need to reference Usercontrol(ascx) in ASPX page in more than one place with different results

百般思念 提交于 2019-12-24 23:59:17

问题


Scenario : Default.aspx is as below.

<%@ Page MasterPageFile="~/StandardLayout.master" Language="C#" CodeFile="Default.aspx.cs"     Inherits="_Default" %>
<%@ Register src=  "~/Controls/Us.ascx" tagname="AboutUs" tagprefix="site" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
    <div id="large">
       <site:AboutUs  ID="AboutUsControl" runat="server" />
    </div>
   <div id="small">
      <site:AboutUs  ID="AboutUsControl" runat="server" />
    </div>
</asp:Content>

AboutUs.ascx.cs assigns some value to a label control. In the above scenario, I want to re-use AboutUs within "div id=small" as the logic is same but only value change.

My question is within AboutUs.ascx.cs, I need some way to find out if it belongs within "", assign Label1 = "I am here". Otherwise Label1 = "I am everywhere"

I am trying to pass parameters but do I need to anything in the code-behind in default.aspx.cs? or any other suggestions.

Please suggest.


回答1:


Make sure both user controls have unique ID's. I'll use AboutUsControl1 and AboutUsControl2. Declare a name property for your user control:

private string _doWhat;
    public string doWhat
    {
        get { return _doWhat; }
        set { _doWhat = value; }
    }

    //Execute the check somewhere in your code to set the text you want.    
    private void Do_Something()
    {
        if (_doWhat == "Large")
        {
            //display "I am here"
        }
        else
        {
            //display "I am everywhere"
        }
    }

And in the code behind on the page using the user controls, just pass the value by calling the public variable:

AboutUsControl1.doWhat = "Large";
        AboutUsControl2.doWhat = "Small";

or just set doWhat in the control itself:

<site:AboutUs ID="AboutUsControl1" runat="server" doWhat="Large" />
<site:AboutUs ID="AboutUsControl2" runat="server" doWhat="Small" />


来源:https://stackoverflow.com/questions/8618656/need-to-reference-usercontrolascx-in-aspx-page-in-more-than-one-place-with-dif

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!