2

私はいくつかのコントロールを追加しているサイトマスターを持っています.1つはプログラムで更新されるラベルです。サイト マスターでスコープがどのように機能するかについての私の理解が間違っている可能性があるため、2 番目の例でオブジェクトを参照できない理由がわかりません。どんな援助でも大歓迎です!

この「ClubName」ラベルは意図したとおりに機能します

 <div class="main">
     <asp:Label ID="ClubName" runat="server"></asp:Label>
</div>

これはそうではありませんが(オブジェクト参照がオブジェクトのインスタンスに設定されていません)

<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
                <AnonymousTemplate>
                    [ <a href="~/Account/Login.aspx" ID="HeadLoginStatus" runat="server">Log In</a> ]
                </AnonymousTemplate>
                <LoggedInTemplate>
                    Welcome <span class="bold"><asp:LoginName ID="HeadLoginName" runat="server" /></span>!
                    [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/"/> ]
                    <asp:Label ID="ClubName" runat="server" Text="Label"></asp:Label>
                </LoggedInTemplate>
 </asp:LoginView>

私のコードビハインドコードは単純です

public partial class SiteMaster : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        NameClub.Text = "hello";
    }

および例外エラー:

 Object reference not set to an instance of an object.
 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
4

2 に答える 2

2

これはすでに回答を得ていますが、LoginView を理解するために重要な情報をもう 1 つ追加するだけです。

The `LoginView` control, when being added onto a page, at a certain time,
only one Template (anonymous or loggedIn ) is applied on the Control
instance, so at that time, we can only retrieve the reference of those
controls in the currently active template( This means we  can't access 
controls in the non-active template).

したがって、ユーザーが認証されているかどうかを判断し、 を使用しLoginView.FindControl( stringId) てコントロール参照を取得することは常に良いことです。そうしないと、再びエラーが表示されます。Object reference not set to an instance of an object.

于 2013-08-16T04:48:04.180 に答える
2
Label ClubName= HeadLoginView.FindControl("ClubName") as Label;
if(ClubName != null)
     ClubName.Text =   "hello";

aspx ラベル ID はありClubNameますが、コードでは としてアクセスしますNameClub。とにかく、LoginView 内のコントロールに直接アクセスすることはできません。FindControlメソッドを使用して、上記のようにコントロールを取得します。

方法: ID によるサーバー コントロールへのアクセスをお読みください。

于 2013-08-16T04:05:37.500 に答える