TheWebs
TheWebs

Reputation: 12923

Concatenating strings in Razor

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?

Upvotes: 121

Views: 156346

Answers (6)

Mohammad Komaei
Mohammad Komaei

Reputation: 9676

<EditBtn Href=@($"ProductAddEdit/{product.Id}") />

( Href is a parameter of my custom component EditBtn )

Upvotes: 0

Sheriff
Sheriff

Reputation: 868

You can give like this....

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

Upvotes: 11

Pajoc
Pajoc

Reputation: 104

You can use:

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

Upvotes: 0

d384
d384

Reputation: 51

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

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

Upvotes: -4

Stephen Reindl
Stephen Reindl

Reputation: 5829

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

Upvotes: 279

Simon
Simon

Reputation: 6152

String.Format also works in Razor:

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

Upvotes: 11

Related Questions