Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a class attribute to Sitecore MVC Link Field without overwriting the style class

Tags:

razor

sitecore

Based on the question/answer here, I can successfully render a field with a class attribute.

For example, I have a list of link fields that are being rendered with the Bootstrap class nav-link. However, if any of the links have Style class: defined in Sitecore, setting the nav-link class will overwrite the style class, rather than add to it.

How can I add the nav-link class without overwriting any classes added through Sitecore?

Example code:

@Html.Sitecore().Field("Link", navItem, new { @class = "nav-link" })

like image 258
Xalor90 Avatar asked Nov 28 '25 19:11

Xalor90


1 Answers

I discovered the answer by casting the field as a LinkField as follows:

@Html.Sitecore().Field("Link", navItem, new { @class = "nav-link " + ((LinkField)navItem.Fields["Link"]).Class, text = Html.Sitecore().Field("Link Text", navItem) })

As can be seen in the code above, we simply concatenate the desired class with ((LinkField)navItem.Fields["Link"]).Class, and that gives us both classes on the field.

like image 94
Xalor90 Avatar answered Dec 01 '25 20:12

Xalor90



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!