Adding a CSS class to razor @Html.DisplayFor

老子叫甜甜 提交于 2020-01-02 06:44:08

问题


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?


回答1:


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"])"...



回答2:


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.



来源:https://stackoverflow.com/questions/18685432/adding-a-css-class-to-razor-html-displayfor

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