Search code examples
c#asp.nettwitter-bootstrapeventsdynamic-list

How to combine ASP with Bootstrap with dynamic lists


My job is to maintain an ASP site, and Bootstrap is great, but there seems to be a fundamental problem with creating a list of items from code-behind, with plain html elements to be displayed nicely with Bootstrap, and to get that list to interact with code-behind.

For example:

<div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">
        <span id="span_selectedclient" runat="server">Dropdown Example</span>
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" id="ul_selectclients" runat="server"
        OnServerChange="SelectClients_Change" onchange="__doPostBack()">
    </ul>
</div>

I can add <li> from code-behind, but the ul element does not have any events, so clicking on a value in the dropdown does not reach the code-behind.

Same for menus.

You can stick an

<a id="abc" runat="server" onserverclick="OnClickHandler">itemtext</a> 

in the <li> elements, but not from code-behind, or the onserverclick event will not work.

Is there a smart trick to make dynamic lists in bootstrap items work with code-behind?


Hmmmmm, perhaps something with __doPostBack() ...


Solution

  • The easy answer is to use __doPostBack().

    Coincidentally, I already mentioned this call in the example, but there my focus was on OnServerChange that you should not insert to client-side code because it should be interpreted server-side.

    But __doPostBack() is interpreted client-side and will work.

    The only thing is that, lacking the server-generated ClientID as a parameter to that call, you cannot have a nice callback function in code-behind, but have to handle the event in Page_Load(), but this is not very hard. Just invent a nice param string to pass to _doPostBack.