Replace items in html template by C# object property values

12,968

Solution 1

I would change your page to use an xslt. This is a really easy way to do replacing of things from the database. The only work you'd have to do then is make your XML document with the data from your database.

Solution 2

If your page is valid XML (as I'm guessing it is based on the example), then you could parse it into an XElement and do a descendant search by node name. You can probably write a more efficient version, but an example would be:

.NET 3.5

    public void Page_Load(object sender, EventArgs e)
    {
        Person person = new Person { FirstName = "Hello", LastName = "World" };
        var dictionary = typeof(Person).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .ToDictionary(p => p.Name.ToUpperInvariant(), p => (p.GetValue(person, null) ?? string.Empty).ToString());
        var xe = XElement.Parse(File.ReadAllText(HttpContext.Current.Server.MapPath("~/template.htm")));
        foreach (var key in dictionary.Keys)
        {
            foreach (var match in xe.Descendants(key))
            {
                match.ReplaceAll(dictionary[key]);
            }
        }
    }

.NET 2.0 Friendly:

        var person = new Person();
        person.FirstName = "Hello"; 
        person.LastName = "World";
        var dictionary = new Dictionary<string, string>();
        foreach(var propertyInfo in typeof(Person).GetProperties(BindingFlags.Public|BindingFlags.Instance))
        {
            var elementName = propertyInfo.Name.ToUpperInvariant();
            var value = (propertyInfo.GetValue(person, null) ?? string.Empty).ToString();
            dictionary.Add(elementName,value);
        }
        var xml = new XmlDocument();
        xml.LoadXml(File.ReadAllText(HttpContext.Current.Server.MapPath("~/template.htm")));
        foreach(var key in dictionary.Keys)
        {
            var matches = xml.GetElementsByTagName(key);
            for(int i = 0; i<matches.Count;i++)
            {
                var match = matches[i];
                var textNode = xml.CreateTextNode(dictionary[key]);
                match.ParentNode.ReplaceChild(textNode, match);
            }
        }

Solution 3

I would use an SqlDataSource and a Repeater control. They make it very easy to pull your data from the database, and then display it on the page. You wouldn't need to do any code-behind as everything would be handled for you by .NET.

Your data source would look something like this:

<asp:sqlDataSource ID="mySqlDataSource" SelectCommand="SELECT firstName, lastName FROM tablename" />

And then you need a control that can use the returned data and display it on the page:

<asp:Repeater runat="server">
    <HeaderTemplate>
        <table>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>First Name: <%#Container.DataItem("firstName")%>"</td>
        </tr>
        <tr>
            <td>Last Name: <%#Container.DataItem("lastName")%></td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>

Edit:

Since you don't want to use a datasource and a databound control, I would recommend the XmlTextWriter class. There is a very good tutorial here. This would allow you to be more flexible than if you were reading the template from a separate HTML file.

Solution 4

Since you are generating an email consider using MailDefinition.CreateMailMessage. You will have to copy the placeholders and replacement values to a Dictionary object.

Share:
12,968
gbs
Author by

gbs

Updated on August 21, 2022

Comments

  • gbs
    gbs over 1 year

    1: I have a .html file that has some markup with some placeholder tags.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
       First Name : <FIRSTNAME/>   <br />
       Last Name:  <LASTNAME/>
    </body>
    </html>
    

    2: I have a Class to hold data returned from db

    public class Person
    {
        public Person()
        {
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    3: PersonInfo.aspx I write out this .html with the placeholder replaced by actual values.

    public partial class PersonInfo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Person per= new Person();
            per.FirstName = "Hello";
            per.LastName = "World";
    
            string temp = File.ReadAllText(Server.MapPath("~/template.htm"));
            temp = temp.Replace("<FIRSTNAME/>", per.FirstName);
            temp = temp.Replace("<LASTNAME/>", per.LastName);
            Response.Write(temp);
        }
    }
    

    4: PersonInfo.aspx is literally empty since I am injecting html from code-behind.

    When the PersonInfo.aspx is called the html-template markup with appropriate values in the placeholder will be displayed. Also there are chances I would like to send the final markup in an html email (though that is not part of the question as I know how to email).

    Is this the best way to fill values in my html-template or is the any other better alternative?

    Note: This is a very simple sample example. My class is very complex involving objects as properties and also my html template have 40-50 placeholders.

    So code in my step 3 will need 40-50 Replace statements.

    Feel free to ask if any doubts and really appreciate any inputs.