Concantenate为DisplayFor字符串 [英] Concantenate a string for DisplayFor

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

问题描述

我有一个模型叫行。它我有一个包含若干字符串,即一类地址:

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服务调用回外线,然后填充返回数据这些领域 - 注:在某些情况下,他们可能不返回一切,让县或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 ,,, POST code,县,乡村 - -

然而,当返回所有数据如果某些字段为空,将显示如它工作正常,即场它没有一个值不会被打印,但将其犯规逗号看起来非常好。我的想法是另一个字符串添加到我的模型如下图所示。

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

我会做一个更换双逗号等取决于该值。每个值检查,但也许在什么替换之前string.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?

对于我来说任何一个可以帮助进一步或者建议一个更好的解决方案?

Can any one help further or perhaps advise a better solution for me?

推荐答案

添加您在一个列表,例如想要的字符串:

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);
}

然后加入字符串:

Then join the strings:

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

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

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