I would like to create the following markup
<tr onclick="toggle(110)" data-order-id-110=110><td>foo</td></tr>
the important part is the data-attribute data-order-id-110=110
. For every item in my model the id (here 110) should be written as a data-attribute that includes the id
in this case 110
.
According to my understanding of Explicit Razor expressions
Any content within the @() parenthesis is evaluated and rendered to the output.
it should be good enough to write
// this code
data-order-id-@(@order.Id)[email protected]
// actual returns
data-order-id@(@order.id)="1"
// expected
data-order-id-1="1"
So besides @(@)
i also tried @{=@}
like this
data-order-id-@(@order.Id)[email protected]
data-order-id-@{[email protected]}[email protected]
Both did not work, see below.
My code
I tried
<tr onclick="toggleOrderDetails(@order.Id)"
data-order-id-@(order.Id)[email protected]>
which returns
<tr onclick="toggleOrderDetails(1)" data-order-id-@(order.id)="1">
.....
</tr>
and also tried
@foreach (var order in Model.Orders)
{
<tr onclick="toggleOrderDetails(@order.Id)" data-order-id-@{[email protected]}[email protected]>
<td>@order.Id</td>
<td>@order.CustomerId</td>
<td>@order.OrderDate</td>
</tr>
}
The html output
<tr onclick="toggleOrderDetails(1)" data-order-id-@{="1}=1">
<td>1</td>
<td>1</td>
<td>26.08.2021 10:30:00</td>
</tr>
As you can see insteald of data-order-id-1=1
the string data-order-id-@{="1}=1
is created.
- expected:
data-order-id-1=1
- actual:
data-order-id-@{="1}=1
Others have mentioned to us @:
but this does not work
Installed version
dotnet --info
returns
.NET Core SDK (reflecting any global.json):
Version: 3.1.118 Commit: 42170158ee
Host (useful for support):
Version: 3.1.18 Commit: 5d3919d34e
.NET Core SDKs installed:
3.1.118 [C:\Program Files\dotnet\sdk]
.NET Core runtimes installed:
Microsoft.AspNetCore.App 3.1.18
Microsoft.NETCore.App 3.1.18
Microsoft.WindowsDesktop.App 3.1.18
The assemply for class MvcServiceCollectionExtensions
is
#region Assembly Microsoft.AspNetCore.Mvc
, Version=3.1.0.0, Culture=neutral
, PublicKeyToken=adb9793829ddae60
// Microsoft.AspNetCore.Mvc.dll
#endregion
Questions
What do i need to concatenate an html data-attribute with a property from a model
CodePudding user response:
I was able to solve it like this
@foreach (var order in Model.Orders)
{
string attribute = "data-order-id-" @order.Id;
<tr onclick="toggleOrderDetails(@order.Id)" @(attribute)[email protected]>
}
This returns this markup
<tr onclick="toggleOrderDetails(1)" data-order-id-1="1">
....
</tr>