Razor语法 - 在字符串中使用两个变量 [英] Razor syntax - using two variables in string
问题描述
SomeObject record = new SomeObject();
record.value1 = 1;
record.value2 = "hello";
<td><input type="checkbox" id="indicator_@record.value1_@record.value2" /><td>
什么是正确的razor语法来创建一个id为indicator_1_hello的复选框?
What is the proper razor syntax to create a checkbox with an id of "indicator_1_hello"?
尝试这种方式时,它表示对象不包含value1_(可理解)的定义,当我尝试indicator_@record.value1 @ _ @ record.value2if
When attempting this way, it says the object doesn't contain a definition for value1_ (understandable) and when I tried "indicator_@record.value1@_@record.value2" if had a runtime error about something named _ not existing in the context (again, understandable).
编辑:
作为一个临时解决方案,我做了:
As a temporary solution I've done:
SomeObject record = new SomeObject();
record.value1 = 1;
record.value2 = "hello";
var combined = String.Format("{0}_{1}", record.value1, record.value2);
<td><input type="checkbox" id="indicator_@combined" /><td>
我仍然很好奇,如果你可以做所有内联。
I am still curious if you can do it all inline though.
推荐答案
@{
// just for testing
var record = new { value1 = "foo", value2 = "bar" };
}
<input type="checkbox" id="indicator_@( record.value1 + "_" + record.value2 )">
提供:< input type =checkboxid =indicator_foo_bar >
只需确保您不是构建一个ID,它会更好地由视图模型的自然层次结构自动生成中。大多数情况下,您不需要在视图中手动构建ID。
Just make sure that you aren't building an ID which would be better auto-generated by the natural hierarchy of your view model. Most of the time, you shouldn't need to manually construct IDs in your view.
这篇关于Razor语法 - 在字符串中使用两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!