Pregunta

I'm in the process of adding some MVC pages to an already existing WebForms project. I want to continue with as few changes as possible to the WebForms master page / helper methods. The WebForms project was using an asp:Menu to build the menu navigation, so I made a HTML helper method which builds the same menu dynamically, renders the control to a HtmlWriter wrapping a StringBuilder, and then returns the output.

Here's my code:

    <Extension()> _
    Public Function RenderMenu(helper As HtmlHelper) As MvcHtmlString
        'Build menu with asp .net standard menu control
        Dim menuSource As New System.Web.UI.WebControls.SiteMapDataSource() With {
            .ShowStartingNode = False,
            .SiteMapProvider = "MySiteMapProvider"
        }

        Dim menuBuilder As New System.Web.UI.WebControls.Menu() With {
            .CssClass = "menu",
            .IncludeStyleBlock = "false",
            .Orientation = System.Web.UI.WebControls.Orientation.Horizontal,
            .StaticSubMenuIndent = New System.Web.UI.WebControls.Unit(20),
            .RenderingMode = System.Web.UI.WebControls.MenuRenderingMode.List,
            .DataSource = menuSource
        }
        menuBuilder.DynamicHoverStyle.BorderStyle = System.Web.UI.WebControls.BorderStyle.Dotted

        Dim buffer As New StringBuilder()
        Dim writer As New System.Web.UI.HtmlTextWriter(New StringWriter(buffer))

        menuBuilder.RenderControl(writer)

        'Convert rendered html to an mvc html string (to avoid re-encoding)
        Return New MvcHtmlString(buffer.ToString())
    End Function

The trouble is, nothing is getting rendered to my HtmlWriter! I've stepped through it on a debugger and confirmed that my menuSource has data. I have also tried manually adding items to the menu, but the same result.

Could this be some kind of an issue with the Page property of the Menu control not being set? If so, is there a way to fake it out?

¿Fue útil?

Solución

You are not calling DataBind() on the menu in this code sample, to bind all the data and create the menu items. Add a call to DataBind().

If that still doesn't work, read in the file and create the menu items programmatically.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top