Cant get the image to show in Umbraco7 with razor - asp.net

I have used the media picker as data type for the type, for which the user is going to choose what image they want as the deal image.
But for some reason i can't get the razor syntax to show the image. If I make an If statement to check if the page contains an image then it won't. I think this is a problem that occurs because i have misunderstood something.
My current razor statement:
<img src="#Umbraco.TypedMedia(Model.Content.GetPropertyValue("deal1image")).Url" />
The above code won't show anything.
Hope any of you can guide me to what i do wrong and evt. stuff I'm missing.
This is how my current home.cshtml looks like:
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#{
Layout = "Master.cshtml";
}
<div class="container">
<div class="col-md-4">
<!--Image here-->
<img src="#Umbraco.Media(CurrentPage.deal1image).Url" />
<div class="thumbnail thumbnailcustom thumbnailbg1">
<h3>#Umbraco.Field("dealtitle1")</h3>
<p>#Umbraco.Field("dealdescription1")</p>
</div>
</div>
<div class="col-md-4">
<!--Image here-->
<div class="thumbnail thumbnailcustom thumbnailbg2">
<h3>#Umbraco.Field("dealtitle2")</h3>
<p>#Umbraco.Field("dealdescription2")</p>
</div>
</div>
<div class="col-md-4">
<!--Image here-->
<div class="thumbnail thumbnailcustom thumbnailbg3">
<h3>#Umbraco.Field("dealtitle3")</h3>
<p>#Umbraco.Field("dealdescription3")</p>
</div>
</div>
</div>

You need to use Umbraco.Media to get the media. So like this
<img src="#Umbraco.Media(Model.Content.GetPropertyValue("deal1image").ToString()).Url" />
Or
<img src="#Umbraco.Media(CurrentPage.deal1image).Url" />

An example of using Umbraco.Media:
var myPage = CurrentPage.AncestorsOrSelf().Where("DocumentTypeAlias == #0", "yourPageAlias").First();
Umbraco.Media(myPage.myImage.ToString()).Url

Link on OUR Umbraco offers two solutions:
Typed:
#if (Model.Content.HasValue("caseStudyImages"))
{
var caseStudyImagesList = Model.Content.GetPropertyValue<string>("caseStudyImages").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse);
var caseStudyImagesCollection = Umbraco.TypedMedia(caseStudyImagesList).Where(x => x != null);
foreach (var caseStudyImage in caseStudyImagesCollection)
{
<img src="#caseStudyImage.Url" style="width:300px;height:300px" />
}
}
Dynamic:
#if (CurrentPage.HasValue("caseStudyImages"))
{
var caseStudyImagesList = CurrentPage.CaseStudyImages.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
var caseStudyImagesCollection = Umbraco.Media(caseStudyImagesList);
foreach (var caseStudyImage in caseStudyImagesCollection)
{
<img src="#caseStudyImage.Url" style="width:300px;height:300px" />
}
}
Also, double check your media picker data type alias. Typos are rather common in this part.

This may be a bit clunky compared to other answers but this is what I currently have.
var imageId = Model.Content.GetPropertyValue<int>("eventPoster"); // gets node id
var evId = evpId.Id; // gets image id
var evMd = Umbraco.Media(evId); // I believe this turns the id into a string
var evUrl = evMd.Url; // gets the url of the string

Related

convert from foreach to for loop

below code working perfectly . but i need to convert it from foreach to for loop .please help me to iteration by for loop. because i have to introduce some if else statement in entire code
#foreach (var item in ViewData["productSl_1"] as IEnumerable<Nazmulkp.Models.Product>)
{
<div class="col-md-3 ">
<div class="thumbnail">
<img src="#Url.Content(item.ImagePath)" alt="Image" style="max-width:100%;">
<div class="caption">
<h5>#item.ProductName</h5>
<h4>Tk.#item.Price</h4>
</div>
</div>
</div>
}
Example:
I have to make sure if index number 2 than execute <div class="col-md-3>"
Thank you
You do not need to convert your foreach to a for loop for adding a conditional css class. Simply add a counter variable to your code and use that for your if condition as needed.
For example, the below code will add the css class "col-md3" to the 3rd item in your collection.
#{ var counter = 0;}
#foreach (var item in YouCollectionHere)
{
<div class="#(counter==2?"col-md-3":"")">
<h2>#item.Name</h2>
</div>
counter++;
}

calling a getJSON function from a button - not working in Chrome/Firefox

I am trying to access the Wikimedia API and display ten results. I have written a function that accesses the API and works on its own.
However, when I try to integrate a Search button to call that function and pass the search string to the function nothing happens in Chrome or Firefox.
(oddly though when I use the snippet function within stackoverflow it works fine!)
I'm wondering why my code doesn't work in the browser - could this have something to do with synchronous/asynchronous behavior and if so what is happening?
I'd really appreciate some insight into what is going on...
Thanks!
$(document).ready(function() {
// Initialize the Global Variables
var api = "http://en.wikipedia.org/w/api.php?callback=?&format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=";
var searchTitle = "";
var searchString = "";
$('#submit').click( function() {
searchTitle = $("input:text").val();
searchString = api + searchTitle;
getWiki(searchString);
});
// the following function works if I call it statically outside of the button click
// for example: getWiki(api + "giraffe");
// but it doesn't work if I call it dynamically from within the button. Why?
function getWiki(val) {
$.getJSON(val, function(json) {
$.each(json.query.pages, function(prop, item) {
var id = "#result" + item.index
$(id).html(item.title + "<br>" + item.extract);
});
});
}
// END Document Ready Function
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
<form class="form-wrapper">
<input type="text" id="search" placeholder="Search for..." required>
<input type="submit" value="go" id="submit">
</form>
<div class="container">
<div class="row">
<div class="col-xs-12">
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
<div id="result4"></div>
<div id="result5"></div>
<div id="result6"></div>
<div id="result7"></div>
<div id="result8"></div>
<div id="result9"></div>
<div id="result10"></div>
</div>
</div>
</div>
</body>

Library.GetMediaById Umbraco Returning Weird String

I am trying to display images in a carousel on my Umbraco from a macro and I am using Library.GetMediaById(child.picture). Here is my code:
#foreach (var child in slider.Children.Where("Visible"))
{
var background = Library.MediaById(child.picture);
if (i == 0)
{
<div id="#i" class="item active" data-id="#i" style="background-image: url(#background.UmbracoFile)">
</div>
}
else
{
<div id="#i" class="item" data-id="#i" style="background-image: url(#background.UmbracoFile)">
</div>
}
i++;
}
However when I do this instead of getting <div id="1" class="item" data-id="1" style="background-image: url('/media/1007/slide-2.png')"></div> like I should I am getting a bunch of extra stuff:
<div id="1" class="item" data-id="1" style="background-image: url({src: '/media/1007/slide-2.png', crops: []})"></div>
How do I just get that media item url and not all the extra stuff?
BTW I am using Umbraco 7.4
If you are using Umbraco 7 or later, I strongly recommend using the new APIs to retrieve property values and content or media nodes, rather than using the Library.MediaById method which is now obsolete.
If you prefer a dynamic view model, you can use the DynamicPublishedContent API, which lets you write dynamic queries using the #CurrentPage model. So your example would be:
#foreach (var child in CurrentPage.AncestorOrSelf(1).Children.Where("isVisible"))
{
var backgroundPicture = Umbraco.Media(child.Picture); //assuming an image property on child
var backgroundPictureUrl = picture.Url;
// your markup here
}
If you instead prefer a strongly typed model, you can use the IPublishedContent API. Please bear in mind that your view must inherit from a suitable type, such as Umbraco.Web.Mvc.UmbracoTemplatePage.
#foreach (var child in Model.AncestorOrSelf(1).Children().Where(c => c.IsVisible))
{
var backgroundPicture = Umbraco.TypedMedia(child.GetPropertyValue<int>("picture");
var backgroupdPictureUrl = backgroundPicture.Url;
// your markup here
}
Also, from your example I'm suspecting that you may be using an image cropper property to store the background image, in which case the property will have a json (JObject) value rather than an int corresponding to the media Id.
In this case, the code retrieving the picture property needs to be adapted, have a look at the documentation for image cropper to see the different ways you can get the image url depending on whether you've specified crops and/or a focal point. As an example, if you're using the dynamic API and you're only interested in the image URL, use the following:
<div style="background-image: url('#child.picture.src')">
So the way I got around this was to, make a partial instead of a macro because partials inherit Umbraco.Web.Mvc.UmbracoTemplatePage so then I could use Umbraco.Media() instead. Here is the working code in case anyone comes across this and needs help:
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#{
var root = Model.Content.AncestorOrSelf(1);
int i = 0;
}
<div class="container">
<div id="photo-carousel" class="carousel slide">
<div class="carousel-inner">
#foreach (var child in root.Children().Where("naviHide == true"))
{
if (child.DocumentTypeAlias.Equals("slider"))
{
foreach (var picture in child.Children.Where("naviHide != true"))
{
var background = Umbraco.Media(picture.GetPropertyValue("picture"));
if (i == 0)
{
<div id="#i" class="item active" data-id="#i" style="background-image: url('#background.Url')">
</div>
}
else
{
<div id="#i" class="item" data-id="#i" style="background-image: url('#background.Url')">
</div>
}
i++;
}
}
}
</div>
<a class="carousel-control left" href="#photo-carousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="carousel-control right" href="#photo-carousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
</div>

Umbraco 7 MVC Razor - Rendering Image (Multinode Tree Picker Script)

I've created a multinode tree picker datatype and i'm trying to list the thumbnails of a vehicle as part of the foreach loop, however i keep getting ID rendering in the src of the image, i'm having trouble getting the URL of the image.
MVC Razor Code
#inherits Umbraco.Web.Macros.PartialViewMacroPage
#using Umbraco.Web
#*
Macro to list nodes from a Multinode tree picker, using the pickers default settings.
Content Values stored as xml.
To get it working with any site's data structure, simply set the selection equal to the property which has the
multinode treepicker (so: replace "PropertyWithPicker" with the alias of your property).
*#
#* Lists each selected value from the picker as a link *#
<div class="featuredVehicles">
#foreach (var id in CurrentPage.featuredVehicles.Split(','))
{
#*For each link, get the node, and display its name and url*#
var vehicleContent = Umbraco.Content(id);
<div class="col-xs-6 col-md-4 col-xs-height">
<a href="#vehicleContent.Url">
#if (vehicleContent.HasValue("vehicleThumbnail"))
{
var mediaItem = Umbraco.TypedMedia(vehicleContent.GetPropertyValue("vehicleThumbnail"));
<img class="featuredVehicleImg img-responsive" src="#vehicleContent.GetPropertyValue("vehicleThumbnail")" alt="#vehicleContent.Name"/>
}
else
{
<img class="comingSoon" src="http://placehold.it/650x408" alt="#vehicleContent.Name">
}
<strong>
<span class="name">#vehicleContent.Name</span>
</strong>
<span class="desc">#vehicleContent.GetPropertyValue("shortContent")</span>
<span class="prx">from, <strong>£#vehicleContent.vehiclePrice</strong> per day</span>
<span class="label label-primary moreinfo">More Info</span>
</a>
</div>
}
</div>
HTML
<img alt="Pharmaceutical Vehicle One" src="1092" class="featuredVehicleImg img-responsive">
Problem solved;
This is the bit where the problems were being caused;
if (vehicleContent.HasValue("vehicleThumbnail")){
var dynamicMediaItem = Umbraco.Media(vehicleContent.vehicleThumbnail);
<img src="#dynamicMediaItem.umbracoFile" alt="#dynamicMediaItem.Name"/>
}
else
{
<img class="comingSoon" src="http://placehold.it/650x408" alt="#vehicleContent.Name">
}
Hopefully it will help someone else out :-)

NopCommerce - Category Images not displaying

I can't get category images to display in a NopCommerce theme. This is the code I'm using, on the CategoryTemplate.ProductsInGridOrLines.cshtml page.
#if (Model.PictureModel != null && !String.IsNullOrWhiteSpace(Model.PictureModel.ImageUrl))
{
<div class="category-picture">
<img alt="#Model.PictureModel.AlternateText" src="#Model.PictureModel.ImageUrl" title="#Model.PictureModel.Title" />
</div>
}
I've tried removing the if statement, and it just generates <img>.
as far as i am aware, category images should be accessed like this..
#foreach (var item in Model.SubCategories)
{
count3++;
<div class="sub-category-item col-4 alignCenter">
<h2 class="title">
<a href="#Url.RouteUrl("Category", new { SeName = item.SeName })" title="#item.PictureModel.Title" class="green">
#item.Name</a>
</h2>
<div class="picture">
<a href="#Url.RouteUrl("Category", new { SeName = item.SeName })" title="#item.PictureModel.Title">
<img alt="#item.PictureModel.AlternateText" src="#item.PictureModel.ImageUrl"
title="#item.PictureModel.Title" /></a>
</div>
</div>
if (count3 %3 == 0)
{
#Html.Raw("</div><div class='row'>")
}
}
this is a slightly modified version of the original nopcommerce code in a site i'm currently working on and this code works.
note that images are taken from the item.pictureModel rather than Model.PictureModel.
this is assuming that you have not moved this code into a separate file.
hope this helps
Before using your code you should add the following code to the Category method in the CatalogController:
//prepare category picture model
int picId = category.PictureId;
int picSize = _mediaSettings.CategoryThumbPictureSize;
var categoryPicCacheKey = string.Format(ModelCacheEventConsumer.CATEGORY_PICTURE_MODEL_KEY, model.Id, picSize, true, _workContext.WorkingLanguage.Id, _webHelper.IsCurrentConnectionSecured(), _storeContext.CurrentStore.Id);
model.PictureModel = _cacheManager.Get(categoryPicCacheKey, () =>
{
var pictureModel = new PictureModel()
{
FullSizeImageUrl = _pictureService.GetPictureUrl(picId),
ImageUrl = _pictureService.GetPictureUrl(picId, picSize),
Title = string.Format(_localizationService.GetResource("Media.Category.ImageLinkTitleFormat"), model.Name),
AlternateText = string.Format(_localizationService.GetResource("Media.Category.ImageAlternateTextFormat"), model.Name)
};
return pictureModel;
});`

Resources