Question

I am trying to generate some HTML code from a VB.NET Web Method and return it as text.

Here's an example markup:

<ul>
    <li>234: this is an item</li>
    <li>456: another item</li>
</ul>

I have some VB thus:

Dim rList As New HtmlGenericControl("UL") ' << create an HTML list container

    Try ' looping through a dictionary of item data
         For j = 0 To UBound(d("itemNo")) ' loiop through all individual item data
             Dim Item = d("itemNo")(j)
             Dim itemName =  d("itemName")(j)
             Dim liItem As New HtmlGenericControl("li") ' << creates an HTML list item
             liItem.InnerHtml += itemNo & ":" & itemName 
             rList.InnerHtml += liItem 
         Next
     Catch ex as Exception
         ' fail case
     End Try

Now, this will generate all the HTML tags and content perfectly well. If I were writing this out to a page, I could do that quite simply.

BUT... I don't want to do that, I want to somehow return the actual HTML markup created by the above code as a text string, ie, I want return rList.toString() to return the markup, but instead it just returns the object type as a string.

I could do this without bothering with the HtmlGenericControl class at all and simply generate a whole load of strings with the opening and closing HTML tags, but the rest of this code is quite complex and there's plenty of room for error... if I could achieve what I am looking for above it'd be much simpler to code!

Was it helpful?

Solution

In order to do this the code should be as follows

Dim rList As New HtmlGenericControl("UL") 

Try 
     // Existing stuff
    Dim stringwriter As New System.IO.StringWriter()
    Dim writer As New HtmlTextWriter(stringwriter)
    rList.RenderControl(writer)
    Return stringwriter.ToString()

 Catch ex as Exception
     ' fail case
 End Try

Good Luck !!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top