asp.net-mvc ASP.NET MVC Razor 连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4702957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:44:32  来源:igfitidea点击:

ASP.NET MVC Razor Concatenation

asp.net-mvcasp.net-mvc-3razorasp.net-mvc-4

提问by David Marchelya

I'm trying the render an HTML list that looks like the following, using the Razor view engine:

我正在尝试使用 Razor 视图引擎呈现一个如下所示的 HTML 列表:

<ul>
  <li id="item_1">Item 1</li>
  <li id="item_2">Item 2</li>
</ul>

The code that I am attempting to use to render this list is:

我试图用来呈现这个列表的代码是:

<ul>
@foreach (var item in Model.TheItems)
{            
  <li id="[email protected]">Item @item.TheItemId</li>
}
</ul>

The parser is choking, because it thinks that that everything to the right of the underscore in the id attribute is plain text and should not be parsed. I'm uncertain of how to instruct the parser to render TheItemId.

解析器很卡,因为它认为 id 属性中下划线右边的所有内容都是纯文本,不应该被解析。我不确定如何指示解析器呈现 TheItemId。

I don't want to but a property on the model object that includes the item_ prefix.

我不想只是包含 item_ 前缀的模型对象上的属性。

I also have to keep this syntax as I am using the list with JQuery Sortable and with the serialize function that requires the id attribute to be formatted in this syntax.

我还必须保留此语法,因为我将列表与 JQuery Sortable 和序列化函数一起使用,该函数要求使用此语法对 id 属性进行格式化。

回答by Matthew Abbott

You should wrap the inner part of the call with ( ):

您应该使用以下内容包装呼叫的内部部分( )

<li id="item_@(item.TheItemId)">

回答by Filip Ekberg

How about using String.Format? like this:

如何使用String.Format?像这样:

<li id="@String.Format("item_{0}", item.TheItemId)">

<li id="@String.Format("item_{0}", item.TheItemId)">

回答by Gary Woodfine

I prefer:

我更喜欢:

<li id="@String.Concat("item_", item.TheItemId)">

The verbosity tells the support developers exactly what is happening, so it's clear and easy to understand.

详细程度会告诉支持开发人员到底发生了什么,因此清晰易懂。

回答by shaijut

You can even use this way to concat more strings:

您甚至可以使用这种方式连接更多字符串

<li id="@("item-"+item.Order + "item_"+item.ShopID)" class="ui-state-default"></li>

Hereis another post.

是另一个帖子。

Hope helps someone.

希望能帮助某人。