Aakanksha Jani
Aakanksha Jani

Reputation: 21

Concatenating strings in cshtml file

How would I join two c# strings in cshtml file?

If I had: @Model.country and @Model.state and I wanted the out put to be country and state what would I do?

Upvotes: 2

Views: 3187

Answers (3)

Yiyi You
Yiyi You

Reputation: 18169

Firstly,If you want to put the value to input,or only want to show them,here is a demo:

    @Model.Country @Model.State
<input value="@Model.Country @Model.State" />

result: enter image description here

If you want to get it in js,here is a demo:

<script>
        $(function () {
            var address = '@[email protected]';
            console.log(address);
        })
    </script>

result: enter image description here enter image description here

Upvotes: 1

Kopadze
Kopadze

Reputation: 51

There are a couple of ways to do that.

  1. You can use @(Model.Country + " " + Model.State) or

  2. with String concat function @string.Concat(Model.Country, " ", Model.State)

  3. Add Readonly Property in ViewModel and use this property to display data. e.g:

      public class IndexViewModel
      {
          public string Country {get;set;}
          public string State {get;set;}
          public string CountryWithState => string.Concat(Country," ", State);
      }
    

Upvotes: 2

Pierre Michel
Pierre Michel

Reputation: 407

@(Model.country + " " + Model.state)

Upvotes: 0

Related Questions