我正在输出一个我想用逗号分隔的地址。如果我在输出地址之前不包含任何 html,它会正确显示,没有任何额外的空格。
例子:
97 Glen Road, 霍利伍德, BT18 0LE
目前获得:
97 格伦路 , 霍利伍德 , BT18 0LE
我的代码是:
    <p class="no-margin-top">@Html.DisplayFor(modelItem => item.Address1)
    @if(!string.IsNullOrEmpty(item.Address2)){
        @:, @Html.DisplayFor(modelItem => item.Address2)
    }
    @if(!string.IsNullOrEmpty(item.Address3)){
        @:, @Html.DisplayFor(modelItem => item.Address3)
    }
    @if(!string.IsNullOrEmpty(item.Town)){
        @:, @Html.DisplayFor(modelItem => item.Town)
    }
    @if(!string.IsNullOrEmpty(item.County)){
        @(", ")@("Co. ")@Html.DisplayFor(modelItem => item.County)
    }
    @if(!string.IsNullOrEmpty(item.Postcode)){
        @(", ")@Html.DisplayFor(modelItem => item.Postcode)
    }
    @if(!string.IsNullOrEmpty(item.Country)){
        @(", ")@Html.DisplayFor(modelItem => item.Country)
    }
如上所示,我尝试以不同的方式输出逗号,但仍然得到相同的结果。
我还尝试从代码中删除所有空格以及使用@Html.Raw。
如果有人对此有解决方案或可以提出更好的方法,将不胜感激。
更新
由于框架内的变化,Darin 的解决方案现在会产生错误。
您需要确保您使用的是 System.Linq
然后修改达林的代码如下:
    public string FormattedAddress
    {
        get
        {
            var values = new[] { Address1, Address2, Address3, Town, Postcode, "Co. " + County }.Where(x => !string.IsNullOrEmpty(x));
            return string.Join(", ", values);
        }
    }