Get media url in View in Sitecore MVC

2019-07-04 04:47发布

I have a mp3 file that is stored in the media library. It is referenced in a media field on an item. I can get the URL by doing Sitecore.Resources.Media.MediaManager.GetMediaURL() in webforms or a class. But how can I achieve this in a MVC view? When I dump the field it just renders a html tag. I want to pull out the url only.

Also, is there a reference for something like this?

Thanks

3条回答
Melony?
2楼-- · 2019-07-04 05:00

You can write an extension method to get the media item URL. Something like this will work (you should add null reference checks btw):

public static string GetMediaUrl(this Sitecore.Mvc.Helpers.SitecoreHelper sitecoreHelper, string fieldName)
{
    return GetMediaUrl(sitecoreHelper, fieldName, sitecoreHelper.CurrentItem);
}

public static string GetMediaUrl(this Sitecore.Mvc.Helpers.SitecoreHelper sitecoreHelper, string fieldName, Item item)
{
    ImageField imageField = item.Fields[fieldName];
    return Sitecore.Resources.Media.MediaManager.GetMediaUrl(imageField.MediaItem);
}

In your cshtml files you can then use:

<a href="@Html.Sitecore().GetMediaUrl("YourMediaField")">Click Here</a>
查看更多
聊天终结者
3楼-- · 2019-07-04 05:15

You need to parse the Raw value of Media or Field using HtmlString before using it in Rendering when using with FieldRenderer.

Though if you can provide more code then it can be answered more accurately because in Sitecore there are many ways (Sitecore ORMs and/or APIs) using which you can render Item Fields.

Also refer this Sitecore MVC project on GitHub and below listed Sitecore MVC videos on YouTube it can prove helpful in long run.

  1. Sitecore MVC - Getting Started (Part 1)
  2. Sitecore MVC -- View Renderings, @Html.Sitecore(), and Custom Models (Part 2)

And there few blog articles by Martina they are good resource on Sitecore MVC parts.

I hope that will be helpful.

Please ask if anything else.

查看更多
放荡不羁爱自由
4楼-- · 2019-07-04 05:18

you have to supply it with the Model that your sending back to your view from the controller:

something like :

Model:

public class c1
{

public string mediaUrl{ get {return Sitecore.Resources.Media.MediaManager.GetMediaURL();}

}

Controller:

ActionResult View1()
{
//prepare you View Values
return View(c1);
}

View:

//the required field should look like this

<a href='@Html.Raw(Json.Encode(Model.mediaUrl))'> Link to File </a>

regards

查看更多
登录 后发表回答