asp:ListView创建一个Case条件

时间:2015-07-23 13:04:15

标签: c# asp.net sharepoint

您好在我的代码下面找到。

我正在尝试为sharepoint创建一个webpart,我可以在滑块中绑定多种类型的项目。

我有两种类型图像视频

每种类型都有不同的标签和格式。所以我不能将值绑定到标签中。我的问题是如何在列表视图中创建类似“SwiCh案例”。

如果type = image - >绑定标记,否则绑定第二个标记。

<asp:ListView runat="server" ID="lvA">
    <LayoutTemplate>
        <div class="slider">
            <ul class="bxslider">
                <asp:PlaceHolder runat="server" ID="itemPlaceHolder" />
            </ul>
    </LayoutTemplate>
    <ItemTemplate>
        <li>
            <!-- "tag A" -->
            <video width="320" height="260" controls>
                <source src="xyz" type="video/mp4">
                Your browser does not support the video tag.
            </video>
        </li>
        <li>
            <!-- "tag B" -->
            <img src="abc" />
        </li>
    </ItemTemplate>
</asp:ListView>

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

  • 视频图片类型设置<asp:PlaceHolder>
  • 在每个Visible的{​​{1}}属性中添加条件。更改适合您项目的条件。

代码在这里:

<asp:PlaceHolder>

更新:您正确地指出在运行时可能会发生错误。如果您无法通过添加对数据的其他检查来避免这些错误,那么还有第二种选择,但它有一些限制。

解决方案是在代码中渲染每个项目。对于每个场景,您都可以创建一个返回HTML的函数:

<ItemTemplate>
    <asp:PlaceHolder runat="server" Visible='<%# Eval("type") == "video" %>'>
        <li>
            <video width="320" height="260" controls>
                <source src="xyz" type="video/mp4">
                Your browser does not support the video tag.
            </video>
        </li>
    </asp:PlaceHolder>
    <asp:PlaceHolder runat="server" Visible='<%# Eval("type") == "image" %>'>
        <li>
            <img src="abc" />
        </li>
    </asp:PlaceHolder>
</ItemTemplate>

每个函数都有一个protected string RenderVideo(System.Data.DataRow dr) { // Get values from the current DataRow string path = dr["path"].ToString(); // Create the appropriate markup for your video return "<video>" + "</video>"; } protected string RenderPhoto(System.Data.DataRow dr) { // Get values from the current DataRow string path = dr["path"].ToString(); // Create the appropriate markup for your video return "<img src='' alt='' />"; } 作为参数。然后,您需要的是在需要时使用当前DataRow调用每个函数。 DataRow可以访问当前DataRow

在下面的示例中,我使用内联if来调用正确的函数。

((System.Data.DataRowView)GetDataItem()).Row

备用:如果您有两个以上的方案,上面使用的内联if效率很低。您可以执行以下几乎相同但更实用的维护。

<ItemTemplate>
    <%#(Eval("type") == "video" ? RenderVideo(((System.Data.DataRowView)GetDataItem()).Row) : RenderPhoto(((System.Data.DataRowView)GetDataItem()).Row)) %>
</ItemTemplate>

这种方法的限制是你不能对每个项目都有ASP控件。