Search code examples
c#.netasp.net-mvc-3html-helperstring-concatenation

Concatenate a string for 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; }

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.

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)

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

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?


Solution

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