I am outputting an address that I would like to comma separate.
If I don’t include any html before outputting the address it is shown correctly without any additional spaces.
Example:
97 Glen Road, Holywood, BT18 0LE
Currently Getting:
97 Glen Road , Holywood , BT18 0LE
My code is:
<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)
}
I have tried outputting the comma differently as shown above but still getting the same result.
I have also tried removing all spaces from the code as well as using @Html.Raw.
Would appreciate it if anyone has a fix for this or could suggest a better way of doing it.
UPDATE
Due to changes within the Framework Darin’s solution will now produce errors.
You will need to ensure you are using System.Linq
Then amended Darin’s code as follows:
public string FormattedAddress
{
get
{
var values = new[] { Address1, Address2, Address3, Town, Postcode, "Co. " + County }.Where(x => !string.IsNullOrEmpty(x));
return string.Join(", ", values);
}
}
WOW, this looks like a terrible mess you’ve ended up in your view. I would recommend you to use a view model and add the following property to your view model that will take care of properly formatting the address:
and then in your view replace the mess with:
and if now you tell me that you have violated all good practices and are not using view models, but are passing directly your domain entities to the view, well, other than telling you that this is wrong you could somehow hack it in the view:
But honestly go use a view model.