问题描述
如何在 cshtml 文件中加入两个 c# 字符串?
如果我有:@Model.country 和 @Model.state 并且我希望输出是国家和州,我会怎么做?
解决方法
有几种方法可以做到这一点。
-
您可以使用
@(Model.Country + " " + Model.State)
或 -
用字符串连接函数
@string.Concat(Model.Country," ",Model.State)
-
在 ViewModel 中添加 Readonly 属性并使用该属性来显示数据。例如:
public class IndexViewModel { public string Country {get;set;} public string State {get;set;} public string CountryWithState => string.Concat(Country,State); }
首先,如果你想输入值,或者只想显示它们,这里有一个演示:
@Model.Country @Model.State
<input value="@Model.Country @Model.State" />
如果你想在js中得到它,这里有一个演示:
<script>
$(function () {
var address = '@Model.Country@Model.State';
console.log(address);
})
</script>
,
@(Model.country + " " + Model.state)