Simsons
Simsons

Reputation: 12735

How to add Dynamic Controls to MasterPage

I am getting my List of Images from JSON and adding to page like below:

IEnumerable jsonData = default(IEnumerable);

            jsonData = GetJsonValues("http://www.viki.com/api/v2/channels.json");

            foreach (MovieDetails item in jsonData)
            {
                Image thumbNailImage = new Image();
                thumbNailImage.ImageUrl = item.Thumbnail;

                //this.Master.Controls.Add(thumbNailImage);
                this.Controls.Add(thumbNailImage);

            }

But this is adding the images at the buttom of the page as the page template comes from master page.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="VikiWeb._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    </asp:Content>

Now how do I add images in Master page.

Upvotes: 1

Views: 2432

Answers (2)

Aristos
Aristos

Reputation: 66641

You place a PlaceHolder in the position you like to add the controls, and add the controls similar to your code, but using this PlaceHolder id as:

<asp:PlaceHolder runat="server" id="placeOnMe" />

and

placeOnMe.Controls.Add(thumbNailImage);

Upvotes: 2

codeandcloud
codeandcloud

Reputation: 55200

Place an asp:Panel in MasterPage where you need the images to be rendered. And in the code-behind of your content page, do this

var panel = Master.FindControl("your_panel_id") as Panel;
if(panel != null)
{
    IEnumerable jsonData = default(IEnumerable);
    jsonData = GetJsonValues("http://www.viki.com/api/v2/channels.json");
    foreach (MovieDetails item in jsonData)
    {
        Image thumbNailImage = new Image();
        thumbNailImage.ImageUrl = item.Thumbnail;
        panel.Controls.Add(thumbNailImage);
    }
}

Upvotes: 1

Related Questions