C# ASP.net 页面中的条件逻辑

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/368169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 00:46:51  来源:igfitidea点击:

Conditional Logic in ASP.net page

c#asp.netconditional

提问by Vidar

I have some code that prints out databse values into a repeater control on an asp.net page. However, some of the values returned are null/blank - and this makes the result look ugly when there are blank spaces.

我有一些代码可以将数据库值打印到 asp.net 页面上的转发器控件中。但是,返回的一些值是空/空白 - 这使得结果在有空格时看起来很难看。

How do you do conditional logic in asp.net controls i.e. print out a value if one exists, else just go to next value.

你如何在 asp.net 控件中执行条件逻辑,即如果存在则打印出一个值,否则就转到下一个值。

I should also add - that I want the markup to be conditional also, as if there is no value I dont want a
tag either.

我还应该补充 - 我希望标记也是有条件的,好像没有值我也不想要
标签。

Here is a snippet of code below just to show the type of values I am getting back from my database. (It is common for Address 2not to have a value at all).

下面是一段代码,只是为了显示我从数据库中获取的值的类型。(地址 2根本没有值是很常见的)。

<div id="results">
    <asp:Repeater ID="repeaterResults" runat="server">
        <ItemTemplate>
             Company:      <strong><%#Eval("CompanyName") %></strong><br />
             Contact Name: <strong><%#Eval("ContactName") %></strong><br />
             Address:      <strong><%#Eval("Address1")%></strong><br />                    
                           <strong><%#Eval("Address2")%></strong><br />..................

Many thanks

非常感谢

采纳答案by Matt Woodward

It's going to be a pretty subjective one this as it completely depends on where and how you like to handle null / blank values, and indeed which one of those two you are dealing with.

这将是一个非常主观的问题,因为它完全取决于您喜欢在何处以及如何处理空值/空白值,以及您正在处理这两个值中的哪一个。

For example, some like to handle nulls at the database level, some like to code default values in the business logic layer and others like to handle default / blank values at the UI - not to mention the plethora of options in between.

例如,有些人喜欢在数据库级别处理空值,有些人喜欢在业务逻辑层编写默认值,而其他人喜欢在 UI 处理默认值/空白值——更不用说中间的过多选项了。

Either way my personal choice would be to make sure you display that no data was available for that field at the UI level to avoid confusion. At worst something along the lines of:

无论哪种方式,我的个人选择都是确保在 UI 级别显示该字段没有可用数据以避免混淆。最坏的情况是:

<strong><% If (Eval("Address2").Length > 0) Then %><%#Eval("Address2")%><% Else %>No data available for Address 2<% End If %></strong><br />

That way at least the user knows that no data is available, rather than not knowing if there has been some system / administrative error.

这样至少用户知道没有可用的数据,而不是不知道是否存在某些系统/管理错误。

Hope that helps :)

希望有帮助:)

回答by Jeff.Crossett

You can use IsDBNull(obj)

您可以使用 IsDBNull(obj)

If IsDbNull(<%#Eval("Address2")%>) then
     etc
End If

回答by Aleksandar

There are may ways to do that, I'm usually using repeater's event OnItemDataBound event that occurs when repeater's item is bound to a data item.

有很多方法可以做到这一点,我通常使用转发器的事件 OnItemDataBound 事件,该事件在转发器的项目绑定到数据项时发生。

To explain OnItemDataBound event let's assume that we have repeater with one field that is always displayed (Name) and optional field that is displayed if is not null (Optional). Further more we want to display some predefined value if optional field is null or empty.
To do this we need first to set repeater's OnItemDataBound event to point to a method, And also to build repeater's item template. We could use any server control within repeater's item template that we can reference later in OnItemDataBound method.

为了解释 OnItemDataBound 事件,让我们假设我们有一个转发器,其中一个字段始终显示(名称),而可选字段如果不为空则显示(可选)。此外,如果可选字段为 null 或为空,我们希望显示一些预定义的值。
为此,我们首先需要将转发器的 OnItemDataBound 事件设置为指向一个方法,并且还要构建转发器的项目模板。我们可以在中继器的项目模板中使用任何服务器控件,我们稍后可以在 OnItemDataBound 方法中引用这些控件。

<asp:Repeater ID="repeaterResults" runat="server"   OnItemDataBound="repeaterResult_ItemDataDataBound">
    <ItemTemplate>
    <strong><%#Eval("Name") %></strong>
    <asp:Literal runat="server" ID="ltlOption" />
    <br />
    </ItemTemplate></asp:Repeater>

Further let's suppose that we will bind a collection of simple objects that are having two properties :Name and Option like follows:

进一步假设我们将绑定一组具有两个属性的简单对象:Name 和 Option,如下所示:

public class SimpleEntity
{
    public string Name {get;set;}
    public string Option {get;set;}
}

Next we will implement repeaterResult_ItemDataDataBound method as follows:

接下来我们将实现repeaterResult_ItemDataDataBound方法如下:

protected void repeaterResult_ItemDataDataBound(object sender, RepeaterItemEventArgs e)
{
  SimpleEntity ent = e.Item.DataItem as SimpleEntity;
  Literal ltlOption = e.Item.FindControl("ltlOption") as Literal;
  if (ent != null && ltlOption != null)
  {
     if (!string.IsNullOrEmpty(ent.Option))
     {
        ltlOption.Text = ent.Option;
     }
     else
     {
        ltlOption.Text = "Not entered!";
     }

  }
}

As method above is implemented, we will display optional field if exists, while if optional field is null or empty string we will display predefined string "Not entered!".

上面的方法实现后,如果存在可选字段,我们将显示,而如果可选字段为空或空字符串,我们将显示预定义的字符串“未输入!”。

回答by Ihar Voitka

I suggest wrapping each key/value pair into custom control with 2 properties. This control will display itself only if value is not empty:

我建议将每个键/值对包装到具有 2 个属性的自定义控件中。仅当 value 不为空时,此控件才会显示自身:

 <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ShowPair.ascx.cs" Inherits="MyWA.ShowPair" %>

<% if (!string.IsNullOrEmpty(Value))
   { %>
<%=Key %> : <%=Value %>
<% } %> 

And then put controls into repeater template:

然后将控件放入转发器模板中:

<asp:Repeater runat='server' ID="repeater1">
     <ItemTemplate>
        <cst:ShowPair Key="Company Name:" Value="<%#((Company)Container.DataItem).CompanyName %>" runat="server"/>
        <cst:ShowPair Key="Contact Name:" Value="<%#((Company)Container.DataItem).ContactName %>" runat="server" />
        <cst:ShowPair Key="Address 1:" Value="<%#((Company)Container.DataItem).Address1 %>" runat="server" />
     </ItemTemplate>
    </asp:Repeater>

回答by Paul

I realise that this is a very old question, but I'd like to add that perhaps the best way of handling this issue is more at the database level, and yes - I know that the OP hasn't specified any type of data source.

我意识到这是一个非常古老的问题,但我想补充一点,也许处理这个问题的最佳方法更多是在数据库级别,是的 - 我知道 OP 没有指定任何类型的数据源.

I'm simply going to assume (yes - ass of you and me) that the current language being used is at least Transact SQL.

我只是假设(是的 - 你和我的屁股)当前使用的语言至少是 Transact SQL。

To this end, I tend to use the data source to produce compound fields. In the case of an address ISNULLwill happily test to see which fields are in use, and return a default value if a NULL field is encountered. On top of this, a separator character(s) can be included to allow for line breaks in the target output medium. One option is to use comma + one space as a delimiter ', '.

为此,我倾向于使用数据源来生成复合字段。在地址的情况下,ISNULL会很乐意测试以查看哪些字段正在使用,如果遇到 NULL 字段,则返回默认值。最重要的是,可以包含一个或多个分隔符以允许在目标输出介质中换行。一种选择是使用逗号 + 一个空格作为分隔符', '

SELECT 
    ISNULL(src.address1 + ', ', '') +
    ISNULL(src.address2 + ', ', '') +
    ISNULL(src.address3 + ', ', '') +
    ISNULL(src.address4 + ', ', '') +
    ISNULL(src.postalcode, '') AS CompoundAddress
...

This works by using NULLagainst itself - adding to NULLreturns a NULL, therefore the value returned will either contain our comma + space or it will return an empty string.

这通过NULL针对自身使用- 添加到NULL返回 a NULL,因此返回的值将包含我们的逗号 + 空格或它将返回一个空字符串。

Something similar can be done to 'trick' Microsoft Access into producing your address field...

可以做类似的事情来“欺骗”Microsoft Access 来生成您的地址字段......

SELECT 
    (src.address1 + ', ') & 
    (src.address2 + ', ') & 
    (src.address3 + ', ') & 
    (src.address4 + ', ') & 
    (src.postalcode) As CompoundAddress
...

In this case the ampersand will convert the NULLto an empty string, but the same still applies to the the addition of the string to the potentially NULLfield.

在这种情况下,&符号将转换NULL为空字符串,但同样适用于将字符串添加到潜在NULL字段。

So now, we can output our address properly in the HTML...

所以现在,我们可以在 HTML 中正确输出我们的地址......

<div id="results">
    <asp:Repeater ID="repeaterResults" runat="server">
        <ItemTemplate>
            Company:      <strong><%#Eval("CompanyName") %></strong><br />
            Contact Name: <strong><%#Eval("ContactName") %></strong><br />
            Address:      <strong><%#Eval("CompoundAddress").ToString().Replace(", ", "<br />") %></strong><br />