ASP.Net - 布局中的循环/条件语句

发布于 2024-12-06 07:08:49 字数 720 浏览 0 评论 0原文

来自 PHP,更具体地说是许多 MVC 框架,我习惯于直接在布局中使用 PHP 中的基本 foreachif 结构。现在我正在学习 ASP.NET,我遇到了更多专有概念,例如用于控制循环的 ListView 等...

因此,举一个我想要的示例 要做的事情...

<div id="container">
    <h1 class="header">Title</h1>

    <% For Each item In ItemsCollection %>
        <% If item.Name IsNot Nothing %>
            <h3>This is the layout for <%= item.Name %></h3>
        <% End If %>
        <p><%= item.Content %></p>
    <% Next %>

</div>

然后,除了使 ItemsCollection 可用之外,我在代码隐藏文件中不需要处理太多事情。

这被认为是不好的做法吗?我应该花时间学习 ASP.NET 的专有控件吗?这种方法有具体的限制吗?

Coming from PHP and more specifically many of the MVC frameworks out their, I've been use to using basic foreach and if constructs in PHP directly in the layout. Now that I'm learning ASP.NET I'm presented with more proprietary concepts like a ListView to control looping, etc...

So to give an example of what I want to do..

<div id="container">
    <h1 class="header">Title</h1>

    <% For Each item In ItemsCollection %>
        <% If item.Name IsNot Nothing %>
            <h3>This is the layout for <%= item.Name %></h3>
        <% End If %>
        <p><%= item.Content %></p>
    <% Next %>

</div>

Then there isn't a lot I have to handle in the Code Behind file... besides making ItemsCollection available.

Is This considered Bad Practice? Should I spend the time learning the proprietary controls for ASP.NET? Are there specific limitations of this approach?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

遗弃M 2024-12-13 07:08:49

这可能是主观的,但有大量文档说明为什么创建 ListView 等标准控件。主要好处是关注点分离,并避免“意大利面条代码”,这正是您的示例。

我相信,如果您要在 .NET 中进行开发,那么非常值得花时间学习控件以及这些控件的背景。 .NET 开发的许多功能、生产力、代码清晰度和易用性都取决于此类设计原则。与其他环境相比,它们是否“正确”或“正确”是值得商榷的。

除了以上所有内容...

简而言之,如果您要使用 WebForms 模型在 .NET 中进行开发,那么您应该像 .NET WebForms 开发人员一样进行编码,如果没有其他要求的话原因很可能是 .NET WebForms 开发人员有一天需要维护您的代码。我们都被训练去期待某些事情,而在维护别人的代码时,这样的事情会让我们发疯。

编辑

当然,如果您使用 ASP.NET MVC,您将处于舒适区,我的意见将不适用。

This may be subjective, but there are tons of documentation about why the standard controls such as the ListView were created. The primary benefits is separation of concerns, and avoidance of "spaghetti code", which is exactly what your sample is.

I believe that if you're going to be developing in .NET is is well worth your time to learn the controls, and the background for these controls. A lot of the power, productivity, code clarity, and ease of .NET development is hinged around such design principles. Whether they are "Correct" or "right" compared to other environments is debatable.

All of the above beside...

The short version is that if you're going to be developing in .NET using the WebForms model, you should code like a .NET WebForms developer, if for no other reason than that it's likely that a .NET WebForms developer will need to maintain your code some day. We've all been trained to expect certain things, and stuff like this drives us nuts when maintaining other people's code.

Edit

Of course, if you go with ASP.NET MVC, you'll be in your comfort zone and my opinion will not apply.

饭团 2024-12-13 07:08:49

无需在 ASP.NET 中嵌入这样的代码和标记(有一些例外;))。

相反,您可以拥有一个可绑定到数据源的 ListView 控件;例如:

 <h3>ListView Example</h3>

  <asp:ListView ID="VendorsListView"
    DataSourceID="VendorsDataSource"
    DataKeyNames="VendorID"
    OnItemDataBound="VendorsListView_ItemDataBound"
    runat="server">
    <ItemTemplate>
      <tr runat="server">
        <td>
          <asp:Label ID="VendorIDLabel" runat="server" Text='<%# Eval("VendorID") %>' />
        </td>
        <td>
          <asp:Label ID="AccountNumberLabel" runat="server" Text='<%# Eval("AccountNumber") %>' />
        </td>
        <td>
          <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' /></td>
        <td>
          <asp:CheckBox ID="PreferredCheckBox" runat="server" 
            Checked='<%# Eval("PreferredVendorStatus") %>' Enabled="False" />
        </td>
      </tr>
    </ItemTemplate>
  </asp:ListView>

  <!-- This example uses Microsoft SQL Server and connects   -->
  <!-- to the AdventureWorks sample database. Add a LINQ     -->
  <!-- to SQL class to the project to map to a table in      -->
  <!-- the database.                                         -->
  <asp:LinqDataSource ID="VendorsDataSource" runat="server" 
    ContextTypeName="AdventureWorksClassesDataContext" 
    Select="new (VendorID, AccountNumber, Name, PreferredVendorStatus)" 
    TableName="Vendors" Where="ActiveFlag == @ActiveFlag">
    <WhereParameters>
      <asp:Parameter DefaultValue="true" Name="ActiveFlag" Type="Boolean" />
    </WhereParameters>
  </asp:LinqDataSource>

取自此处。

更新:就条件语句而言,您可以处理 ItemDataBound 事件:

protected void VendorsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
  if (e.Item.ItemType == ListViewItemType.DataItem)
  {
    ListViewDataItem dataItem = (ListViewDataItem)e.Item;
    string vendorID= (string)DataBinder.Eval(dataItem, "VendorID");
    // ...
  }
}

There's no need to embed code and markup like this in ASP.NET (With some exceptions ;)).

Instead, you can have a ListView control that you can bind to a DataSource; for example:

 <h3>ListView Example</h3>

  <asp:ListView ID="VendorsListView"
    DataSourceID="VendorsDataSource"
    DataKeyNames="VendorID"
    OnItemDataBound="VendorsListView_ItemDataBound"
    runat="server">
    <ItemTemplate>
      <tr runat="server">
        <td>
          <asp:Label ID="VendorIDLabel" runat="server" Text='<%# Eval("VendorID") %>' />
        </td>
        <td>
          <asp:Label ID="AccountNumberLabel" runat="server" Text='<%# Eval("AccountNumber") %>' />
        </td>
        <td>
          <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' /></td>
        <td>
          <asp:CheckBox ID="PreferredCheckBox" runat="server" 
            Checked='<%# Eval("PreferredVendorStatus") %>' Enabled="False" />
        </td>
      </tr>
    </ItemTemplate>
  </asp:ListView>

  <!-- This example uses Microsoft SQL Server and connects   -->
  <!-- to the AdventureWorks sample database. Add a LINQ     -->
  <!-- to SQL class to the project to map to a table in      -->
  <!-- the database.                                         -->
  <asp:LinqDataSource ID="VendorsDataSource" runat="server" 
    ContextTypeName="AdventureWorksClassesDataContext" 
    Select="new (VendorID, AccountNumber, Name, PreferredVendorStatus)" 
    TableName="Vendors" Where="ActiveFlag == @ActiveFlag">
    <WhereParameters>
      <asp:Parameter DefaultValue="true" Name="ActiveFlag" Type="Boolean" />
    </WhereParameters>
  </asp:LinqDataSource>

Taken from here.

UPDATE: As far as conditional statements, you can handle the ItemDataBound event:

protected void VendorsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
  if (e.Item.ItemType == ListViewItemType.DataItem)
  {
    ListViewDataItem dataItem = (ListViewDataItem)e.Item;
    string vendorID= (string)DataBinder.Eval(dataItem, "VendorID");
    // ...
  }
}
飘过的浮云 2024-12-13 07:08:49

如果您使用普通的 ASP.NET 框架,您的示例不是最佳实践,您应该坚持使用服务器端控制模型。 ASP.NET 被设计为主要用作服务器端控制模型。您所描述的内容与传统 ASP 页面更接近。

例如,Repeater 控件将与您的示例代码完美匹配。

http://msdn.microsoft.com/en -us/library/system.web.ui.webcontrols.repeater.aspx

粗略示例:

标记:

<asp:Repeater id="Repeater1" runat="server">
    <HeaderTemplate>
        <div id="container">
            <h1 class="header">Title</h1>
    </HeaderTemplate>
    <ItemTemplate>
        <h3>This is the layout for <%# DataBinder.Eval(Container.DataItem, "Name") %></h3>
        <p><%# DataBinder.Eval(Container.DataItem, "Content") %></p>
    </ItemTemplate>
    <FooterTemplate>
        </div>
    </FooterTemplate>
</asp:Repeater>

代码隐藏:

protected void Page_Load(Object sender, EventArgs e) 
{
    if (!Page.IsPostBack)
    {
         // create or retrieve some bindable datasource
         // ArrayList values = ....

         Repeater1.DataSource = values;
         Repeater1.DataBind();
    }
}

这是与您的示例相匹配的服务器端控制模型。 Repeater 将根据设计迭代您的项目集合并创建相同的最终结果。它基本上会吐出页眉模板,使用项目模板迭代您的集合,然后吐出页脚模板。还有很多其他选项,这只是一个简单的例子。

If you go with the vanilla ASP.NET framework, your example is not best practice and you should stick with the server-side control model. ASP.NET was designed to be used primarily as a server-side control model. What you describe more closely matches traditional ASP pages.

For example, a Repeater control would match your example code perfectly.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx

Rough example:

Markup:

<asp:Repeater id="Repeater1" runat="server">
    <HeaderTemplate>
        <div id="container">
            <h1 class="header">Title</h1>
    </HeaderTemplate>
    <ItemTemplate>
        <h3>This is the layout for <%# DataBinder.Eval(Container.DataItem, "Name") %></h3>
        <p><%# DataBinder.Eval(Container.DataItem, "Content") %></p>
    </ItemTemplate>
    <FooterTemplate>
        </div>
    </FooterTemplate>
</asp:Repeater>

Code behind:

protected void Page_Load(Object sender, EventArgs e) 
{
    if (!Page.IsPostBack)
    {
         // create or retrieve some bindable datasource
         // ArrayList values = ....

         Repeater1.DataSource = values;
         Repeater1.DataBind();
    }
}

That is a matching server side control model to your example. The Repeater will by design iterate through your item collection and create the same end result. It basically spits out the header template, iterates your collection using the item template, and then spits out the footer template. There are lots of other options as well, this is simply a quick example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文