Adding a CSS class to razor @Html.DisplayFor

2019-05-09 02:46发布

I want to set a new class for this part of my code, but it doesn't work correctly

@Html.DisplayFor(model => model.melk.Code, new { @class = "myClass" } )

Can anyone tell me where am I wrong?

2条回答
Summer. ? 凉城
2楼-- · 2019-05-09 03:25

Boris showed you the correct overload, but there is also the dead simple way to just change it to:

<span class="myClass">
    @Html.DisplayFor(model => model.melk.Code)
</span>

Personally, I find it simpler, so easier to remember and maintain, even if it's not so framework-specific.

查看更多
走好不送
3楼-- · 2019-05-09 03:28

The DisplayExtensions.DisplayFor overload that you are using will find the DisplayTemplate based on the type of the model.melk.Code and the last parameter (anonymous object new { @class = "myClass" } will be passed to the template's ViewData. You have to use that ViewData in the corresponding template in order for it to work.

<div class="@(ViewData["class"])"...
查看更多
登录 后发表回答