2

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?

2
  • Does this answer your question? Concatenating strings in Razor Commented Jan 18, 2021 at 7:40
  • Hello,is my answer helpful? Commented Jan 27, 2021 at 1:43

3 Answers 3

2

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);
      }
    
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

1 Comment

A detailed explanation with your answer would help to understand the solution better. Please improve it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.