Concatenating strings in Razor

asp.net Mvcasp.net Mvc-3Razor

asp.net Mvc Problem Overview


How would I join two strings in Razor syntax?

If I had: @Model.address and @Model.city and I wanted the out put to be address city what would I do? Is it as simple as doing @Model.address + " " + @Model.city?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

Use the parentesis syntax of Razor:

@(Model.address + " " + Model.city)

or

@(String.Format("{0} {1}", Model.address, Model.city))

Update: With C# 6 you can also use the $-Notation (officially interpolated strings):

@($"{Model.address} {Model.city}")

Solution 2 - asp.net Mvc

String.Format also works in Razor:

String.Format("{0} - {1}", Model.address, Model.city)

Solution 3 - asp.net Mvc

You can give like this....

<a href="@(IsProduction.IsProductionUrl)Index/LogOut">

Solution 4 - asp.net Mvc

You can use:

@foreach (var item in Model)
{
  ...
  @Html.DisplayFor(modelItem => item.address + " " + item.city) 
  ...

Solution 5 - asp.net Mvc

the plus works just fine, i personally prefer using the concat function.

var s = string.Concat(string 1, string 2, string, 3, etc)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTheWebsView Question on Stackoverflow
Solution 1 - asp.net MvcStephen ReindlView Answer on Stackoverflow
Solution 2 - asp.net MvcSimonView Answer on Stackoverflow
Solution 3 - asp.net MvcSheriffView Answer on Stackoverflow
Solution 4 - asp.net MvcPajocView Answer on Stackoverflow
Solution 5 - asp.net Mvcd384View Answer on Stackoverflow