Get media url in View in Sitecore MVC

2019-07-04 05:05发布

问题:

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

回答1:

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>


回答2:

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



回答3:

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.