thematt
thematt

Reputation: 185

sitecore mvc value of droplink

I am looking for the simplest way to get the referenced item value for a droplink field.

@Html.Sitecore().Field("Alignment")

I want to get the value of the choice, what's the best approach?

Upvotes: 3

Views: 2914

Answers (3)

computerjules
computerjules

Reputation: 316

The Droplink field stores the referenced item's ID. To retrieve this ID (providing the field is present in your current item/model):

((LinkField)Model.Item.Fields["Alignment"]).Value

To output the referenced item's name, you could do something like this:

@(Model.Item.Database.GetItem(((LinkField)Model.Item.Fields["Alignment"]).Value).Name)

But that's really ugly. The preferred approach would be to create an extension method encapsulating some of the above so you're not having to re-type that out :D

The article Extending the SitecoreHelper Class by John West shows how to extend the SitecoreHelper class to add custom field renderers, so you could end up creating a neat re-usable snippet like:

@(Html.Sitecore().ReferenceField("Alignment","Name"))

Upvotes: 1

Aleksey Shevchenko
Aleksey Shevchenko

Reputation: 1241

If you need to have ability to edit fields of alignment item which is chosen in 'Alignment' droplink field of context item or just show values of alignment item's fields for visitors:

@{
    Sitecore.Data.Fields.ReferenceField alignmentField = Sitecore.Context.Item.Fields["Alignment"];
    Sitecore.Data.Items.Item alignmentItem = alignmentField.TargetItem;
}

<div>
    @Html.Sitecore().Field("Text of Alignment", alignmentItem)
</div>

This example assumes that Alignment template contains 'Text of Alignment' field.

Upvotes: 1

denford mutseriwa
denford mutseriwa

Reputation: 538

If this is in a partial view i.e. .cshtml file you can also use something like below:

Sitecore.Data.Fields.TextField alignment= Model.Item.Fields["Alignment"];

This will give you the id of the set item in the drop link , then from that id can retrieve it from the database like:

@if (!string.IsNullOrWhiteSpace(alignment.Value))
{
    var setAlignment = Sitecore.Context.Database.GetItem(alignment.Value);
    if (setAlignment != null && !string.IsNullOrWhiteSpace(setAlignment.Name))
    {
     setAlignment.Name
    }
}

Personally i prefer this way as i can check if the droplink is set before trying to use the value.

Upvotes: 0

Related Questions