【问题标题】:Concatenating strings in cshtml file在cshtml文件中连接字符串
【发布时间】:2021-01-18 06:24:00
【问题描述】:

如何在 cshtml 文件中加入两个 c# 字符串?

如果我有:@Model.country 和 @Model.state,并且我希望输出是国家和国家,我会怎么做?

【问题讨论】:

标签: .net asp.net-mvc asp.net-core razor


【解决方案1】:

有几种方法可以做到这一点。

  1. 您可以使用@(Model.Country + " " + Model.State)

  2. 带字符串连接函数@string.Concat(Model.Country, " ", Model.State)

  3. 在 ViewModel 中添加 Readonly 属性并使用该属性来显示数据。例如:

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

【讨论】:

    【解决方案2】:

    首先,如果你想输入值,或者只想显示它们,这里有一个演示:

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

    结果:

    如果你想在 js 中获取它,这里有一个演示:

    <script>
            $(function () {
                var address = '@Model.Country@Model.State';
                console.log(address);
            })
        </script>
    

    结果:

    【讨论】:

      【解决方案3】:
      @(Model.country + " " + Model.state)
      

      【讨论】:

      • 您的答案的详细解释将有助于更好地理解解决方案。请改进它。
      猜你喜欢
      • 2012-02-24
      • 2013-10-23
      • 2011-06-21
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 2013-01-30
      相关资源
      最近更新 更多