views:

194

answers:

1

I would like to create a HtmlHelper function for a specific kind of dropdown that appears on many pages in my app. I'm basically just trying to add some decoration around the existing DropDownList function, but it's being encoded. Here's my extension method:

    <Extension()> _
    Public Function Year(ByVal HtmlHelper As System.Web.Mvc.HtmlHelper, ByVal name As String) As String

        Return _
            <label>
                Year:
                <%= HtmlHelper.DropDownList(name) %>
            </label>.ToString

    End Function

This returns the following:

<label>Year:&lt;select id="year" name="year"&gt;&lt;option value="2007"&gt;2007&lt;/option&gt;&lt;option value="2008"&gt;2008&lt;/option&gt;&lt;option selected="selected" value="2009"&gt;2009&lt;/option&gt;&lt;/select&gt;</label>

instead of what I want:

<label>Year:<select id="year" name="year"><option value="2007">2007</option><option value="2008">2008</option><option selected="selected" value="2009">2009</option></select></label>

In other words, the DropDownList is HTML encoded before the string is put inside the label. I could do it like this:

    <Extension()> _
    Public Function Year(ByVal HtmlHelper As System.Web.Mvc.HtmlHelper, ByVal name As String) As String

        Return "<label>Year:" & HtmlHelper.DropDownList(name) & "</label>"

    End Function

but I'd rather make use of VB's inline XML. How do I get the results of DropDownList to not be encoded?

+1  A: 

First of all, did you really want the label to surround the dropdown instead of preceding it?

Then, I gather that HtmlHelper.DropDownList(name) returns a string? Then of course, it should be encoded. If you want XML, then you should use something like XElement.Parse(HtmlHelper.DropDownList(name)) instead.

I'm not sure of the syntax to do that inside an XML literal, but this is small enough you could just use straight LINQ to XML:

Dim result as XElement = New XElement("label", _
   XElement.Parse( HtmlHelper.DropDownList(name)))
Return result.ToString()
John Saunders
I could precede it with the label and specify "for", but I'd have the same question if I wanted to put a table or div around the dropdown, for example. It looks like all I was looking for was "Parse" to turn it back from a String to an XML element, because this now works as intended: <%= XElement.Parse(HtmlHelper.DropDownList(name)) %>
gfrizzle