Access body element from content page via a nested master page

前端 未结 2 2252
遇见更好的自我
遇见更好的自我 2021-02-16 00:15

All I want to do is access the element from the code-behind of a content page and add a class name to it.

I have a top-level master page with t

2条回答
  •  遇见更好的自我
    2021-02-16 00:34

    once you have set runat="server" for your body node, you have to access it using the HTMLControls namespace. try this.

    public void Page_Load(Object sender, EventArgs e)
    { 
    //Inject onload and unload
    HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("bodyNode");
    body.Attributes.Add("class", "home-page");   
    }
    

    EDIT
    Your problem is that you have nested master pages.

    Since the "body" tag is in your top level master page, Master.FindControl() won't work, as that is looking in the nested master page.

    What you need to do is use Master.Master.FindControl(), or recursively loop through your master pages, going up until Master.Master is null (as then you know you are at the top level master page) and then calling FindControl() on that.

提交回复
热议问题