连接DisplayFor的字符串 [英] Concatenate a string for DisplayFor

查看:237
本文介绍了连接DisplayFor的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Lines的模型.在它上面我有一个地址类,其中包含许多字符串,即:

I have a model called Lines. On it I have a address class that contains a number of strings, i.e.:

public string ReferenceKey { get; set; }
public string Country { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public string PremisesName { get; set; }
public string PremisesName { get; set; }

我从Web服务调用中获取到外部方的信息,然后使用返回的数据填充这些字段-请注意,在某些情况下,它们可能不会返回所有内容,因此,例如County或PostTown可能会返回为空.

I get information back from a webservice call to an outside party and then populate these fields with the returned data - note in some cases they may not return everything so County or PostTown for example may be returned empty.

当前在我的cshtml页面中,我显示的地址如下:

Currently in my cshtml page I am displaying the address as below:

@Html.DisplayFor(model => model.Address.ReferenceKey),
@Html.DisplayFor(model => model.Address.PremisesName),
@Html.DisplayFor(model => model.Address.PostTown),
@Html.DisplayFor(model => model.Address.Postcode),
@Html.DisplayFor(model => model.Address.County),
@Html.DisplayFor(model => model.Address.Country)

返回所有数据时它工作正常,但是如果某些字段为空白,它将显示为-REF1 ,,,, POSTCODE,County,Country-即不会打印没有值的字段,但是逗号会看起来不是很好.我的想法是向模型中添加另一个字符串,如下所示.

It works fine when all data is returned however if some fields are Blank it would show for e.g - REF1,,,POSTCODE,County,Country - i.e the fields it doesnt have a value for wont be printed but the commas will which doesnt look very good. My idea was to add another string to my model like below.

public string ConcatAddress { get; set; }

现在我有点卡住了-在控制器中,我正在执行以下操作来构建字符串:

Now were I am kind of stuck - in my controller I was doing the below to build up the string:

model.ConcatAddress = model.Address.ReferenceKey + model.Address.PremisesName....etc, etc

我要怎么做才能将双逗号替换为一个,依此类推,取决于值.一个字符串.也许在每个值检查之前是IsNullorEmpty,但是在替换上是什么?

What would I have to do to replace the double commas with one, etc depending on if the value. A string.IsNullorEmpty before each value check perhaps but what on the replace?

推荐答案

在列表中添加所需的字符串,例如:

Add the strings that you want in a list, e.g.:

var str = New List<string>();
if (!string.IsNullOrEmpty(model.Address.ReferenceKey)) {
  str.Add(model.Address.ReferenceKey);
}

然后加入字符串:

return string.Join(",", str);

这篇关于连接DisplayFor的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆