How can I get image parameters from Sitecore MediaItem?

I need to read image parameters (source, width, height) in the controller when I create a json feed.

I took all the steps from this question . But the proposed method allows you to get the image tag using the View Helper and only within the view context. Since I cannot (and really don't want to, as it is really bad practice) to create an HTMLHelper in the controller, I cannot create it.

This method only gives me the path to * .ashx, no matter what I set in my web.config file. So I have this * .ashx url ( /~/media/5EE32493443547ED8DB0B26166209C85.ashx

), but I can't take advantage of that and generate a normal * .jpg url that /~/media/001FC62786B044F5888640C7164ED72F.JPG

.

*. ashx url has ID in it ( 5EE32493-4435-47ED-8DB0-B26166209C85

), but * .jpg is not ...

Also, when I paste the * .ashx url into the browser, the server responds with the exception that the resource was not found.

+3


source to share


1 answer


After searching and testing and testing numerous options for a while, I found a very simple solution:

string mediaUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(item);

      

item

must be a class object Sitecore.Data.Items.MediaItem

.

mediaUrl

the variable has the following meaning: /~/media/001FC62786B044F5888640C7164ED72F.JPG

Based on this simple method, I went back to the question of width and height, and I wrote a simple class (to make it easier to serialize an image to JSON) that shows how to get all the properties from an image added via Sitecore CMS:



public class DataItemImage
{
    public string ID { get; set; }
    public string Source { get; set; }
    public string Width { get; set; }
    public string Height { get; set; }
    public string Alt { get; set; }

    public DemoDataItemImage(Sitecore.Data.Fields.ImageField obj)
    {
        string mediaUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(obj.MediaItem);
        ID = obj.MediaItem.ID.ToString();
        Source = mediaUrl;
        Width = obj.Width;
        Height = obj.Height;
        Alt = obj.Alt;
    }
}

      

I added the parameter Alt

and ID

. There are others like Class

and Border

, but since these things can be set in the frontend (HTML + CSS), I have not added them.

If you want to output this class as Json, set your controller action to return JsonResult

and add this line (where obj

is an instance of the class DataItemImage

):

return Json(obj, JsonRequestBehavior.AllowGet);

      

I hope this helps other Sitecore developers.

+4


source







All Articles