gringo_dave
gringo_dave

Reputation: 1472

How to set EpiServer.Url property programmatically

On my BlockData type I've property of type EpiServer.Url

public virtual EpiServer.Url Url { get; set; }

From EditMode I'm able to set it for concrete PageData instance, but i'm not sure how to set it in code having only ContentReference?

Thanks in advance for help.

EDIT:

The one way I found to do this is through:

var urlResolver = ServiceLocator.Current.GetInstance<UrlResolver>();
int contentReferenceId = 69;
ContentReference contentRef = new ContentReference(contentReferenceId);
block.Url = urlResolver.GetUrl(contentRef, language.Code);

I would be glad if somebody could point me a better solution if there is any.

Upvotes: 1

Views: 1991

Answers (2)

Tomasz Madeyski
Tomasz Madeyski

Reputation: 10890

Because of the way EpiServer.Url class is made (see public static implicit operator Url(string url) implementation) the only way to set value of it in the code is by setting string value:

var url = "some url";
block.Url = url;

So the way you suggest (ContentReference and IUrlResolver) in your question works correct, but I believe I have a better solution which in some cases (when you have PageData instance available) might be much simpler:

EPiServer.Core.PageData has public virtual string LinkURL property. You can use this value and set it as your Url value:

block.Url = articlePage.LinkURL; //articlePage is instance of PageData

EpiServer will understand that this is internal link to some content and will set proper link to content - so whenever you move or rename your content block.Url will still point to valid content.

Upvotes: 1

Johan Petersson
Johan Petersson

Reputation: 1027

publich virtual ContentReference Url { get; set; }

Or if you only want pages:

publich virtual PageReference Url { get; set; }

Upvotes: 1

Related Questions