ASP.NET MVC Razor Concatenation

穿精又带淫゛_ 提交于 2019-12-17 17:34:01

问题


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

<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="item_@item.TheItemId">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.

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

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.


回答1:


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

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



回答2:


How about using String.Format? like this:

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




回答3:


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.




回答4:


You can even use this way to concat more strings:

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

Here is another post.

Hope helps someone.



来源:https://stackoverflow.com/questions/4702957/asp-net-mvc-razor-concatenation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!