Varun Sharma
Varun Sharma

Reputation: 2759

Add class to HTML text (asp .net)

I am having a label control on my page. In the code behind I am calling a web service that returns HTML text directly. For example:

string htmlFromWebService = client.ReturnHTML();
lblMyLabel.Text = htmlFromWebService;

The string htmlFromWebService contains this:

<h1 class='Class1'>
    HTML TEXT
</h1>
<div class='Class2'>
    Text 1<br />
    <br />
    Text 2<br />
    <br />
    Text n<br />
    <br />
</div>

Now I already know that the HTML returned from the web service contains a class called Class2. All I want to do is that - add some (margin, padding etc.) css stlying to that div. How can I do that? I don't want to do string replace like htmlFromWebService.replace("class='Class2'", "class='Class2' cssclass="myclass"");

I would like to know if there is any proper or better way of doing it.

Thanks.

Upvotes: 0

Views: 389

Answers (3)

Gabriel Espinoza
Gabriel Espinoza

Reputation: 413

Sorry the double post, I just found this:

Build HtmlGenericControl from a string of full html

Maybe it can help you, is a way to create a control from a string html. :)

Upvotes: 1

Gabriel Espinoza
Gabriel Espinoza

Reputation: 413

I don't think you can create an object from an html string, if that's what your are asking... If you can't use css (as Karl Anderson said), I recommend using string methods to achieve that functionality.

for example: (note that this code only works if there is only one object with the text defined in stringToSearch)

string stringToSearch = "Class2";
int indexOfClass2 = htmlFromWebService.IndexOf(stringToSearch);
string myAttributes = @" style='background-color: red;'";

string finalHtml = htmlFromWebService.Substring(0, indexOfClass2 + stringToSearch.Length+1);
finalHtml += myAttributes;
finalHtml += htmlFromWebService.Substring(indexOfClass2 + stringToSearch.Length+1);

Upvotes: 1

Karl Anderson
Karl Anderson

Reputation: 34846

Add a style block to your markup, like this:

<style type="text/css">
    h1.Class1 {
        margin: 5px;
        padding: 5px;
    }
    div.Class2 {
        margin: 10px;
        padding: 10px;
    }
</style>

Note: The h1.Class1 syntax is a selector that finds all H1 tags that have a class value of Class1.

OR

Put the CSS into a stylesheet (Example.css), like this:

h1.Class1 {
    margin: 5px;
    padding: 5px;
}
div.Class2 {
    margin: 10px;
    padding: 10px;
}

Then in your markup you will need to reference the stylesheet, like this:

<link rel="stylesheet" type="text/css" href="Example.css" />

Upvotes: 1

Related Questions