combining hyperlinks with razor? - asp.net-mvc

I tried to show dynamic urls stored in my database, but the database only have part of the URL, and I tried something like this, but it's not working, any ideas?
#foreach(var item in Model.dominios)
{
url
}

You don,t need Html.DisplayFor() here. Build your url and put it into the link:
#foreach(var item in Model.dominios)
{
var linkUrl = string.Format("http://www.{0}.sss.com", item.subdom);
link text
}

Related

Umbaco Archtype rendering images (MediaPicker2)

I'm building a image slider using Archtype in Umbraco.
I was using umbraco 7.5.9 and Umbraco.MediaPicker when I started this but in the mean time I started a new project with the newest version Umbraco (7.6.2) which uses Umbraco.MediaPicker2
It was no problem rendering images with the old MediaPicker but with the MediaPicker2 it seems impossible.
Here is my setup.
The Archtype:
Here is the partial view that rendered the old MediaPicker
<div class="fullWidthSlider">
#foreach (var image in #CurrentPage.SliderImages)
{
<div>Id: #image.GetValue("image")</div>#*Line added for debug*#
var media = #Umbraco.Media(image.GetValue("image"));
<img src="#media.Url" />
}
</div>
This used to work for the old Media picker and the #image.GetValue returned int id. But with the new MediaPicker2 it returns Umbraco.Core.Udi[]
If I foreach through the properties of the archtype with the code below I get this result (see below code)
#foreach (var fieldset in Model.Content.GetPropertyValue<ArchetypeModel>("sliderImages"))
{
foreach(var prop in fieldset.Properties){
<p>#prop.Alias - #prop.Value</p>
}
}
href -
altText - alt test
image - umb://media/c33bfe07a82b4df18a79db154139cb91
href -
altText - Fjall
image - umb://media/40d5778d34bb4035b5146c901de75212
Can anyone tell me how I can render image from this data.
Thanks
I just went on a roller-coaster figuring this out!
You can get an IPublishedContent from your image string using this code:
// Your string which is retrieved from Archetype.
var imageString = "umb://media/c33bfe07a82b4df18a79db154139cb91";
// Get the guid from this string.
var imageGuidUdi = GuidUdi.Parse(imageString);
// Get the ID of the node!
var imageNodeId = ApplicationContext.Current.Services.EntityService.GetIdForKey(guidUdi.Guid, (UmbracoObjectTypes)Enum.Parse(typeof(UmbracoObjectTypes), guidUdi.EntityType, true));
// Finally, get the node.
var imageNode = Umbraco.TypedMedia(imageNodeId.Result);
Check out this thread on Our Umbraco which covers this issue.
I used this comment to figure out how to get the ID from the image's guid.
It looks like Umbraco HQ is pushing for people to use the new ModelsBuilder with typed models. I'm not sure if Archetype is supported by the ModelsBuilder which is why there's so much trouble.
I personally use Nested Content on all of my projects as it performs the same functionality but (IMO) is better supported by Umbraco because it uses Document Types to store repeatable content schema. Because of this, it can then easily be mapped to IPublishedContent and therefore is supported by the ModelsBuilder!

Randomly selecting an image from a folder in Umbraco

I have created a folder in Umbraco and I would like to display a random image from that folder on my page.
I found a solution from a few years ago which was giving me compile errors
dynamic folder = Library.MediaById(1054);
var randomImage = folder.Children.Where("nodeTypeAlias = \"Image\"").Random();
I found that I have to add the proper inherits in my file
#using umbraco.MacroEngines
#inherits DynamicNodeContext
but this it gives me an error because I already have a #model I'm using in the first line
The 'inherits' keyword is not allowed when a 'model' keyword is used.
Thanks for any help
You can take a look and learn from sample macro partial views pre-installed in each Umbraco website. There is a snippet called List Images From Media Folder.
The code of the default snippet looks like this:
#inherits Umbraco.Web.Macros.PartialViewMacroPage
#*
Macro to display a series of images from a media folder.
How it works:
- Confirm the macro parameter has been passed in with a value
- Loop through all the media Id's passed in (might be a single item, might be many)
- Display any individual images, as well as any folders of images
Macro Parameters To Create, for this macro to work:
Alias:mediaId Name:Select folder with images Type:Single Media Picker
*#
#{ var mediaId = Model.MacroParameters["mediaId"]; }
#if (mediaId != null)
{
#* Get all the media item associated with the id passed in *#
var media = Umbraco.Media(mediaId);
var selection = media.Children("Image");
if (selection.Any())
{
<ul>
#foreach (var item in selection)
{
<li>
<img src="#item.umbracoFile" alt="#item.Name" />
</li>
}
</ul>
}
}
We need to remember to add the parameter to macro if we're using them there.
Then we can use both: Media or TypedMedia helper methods to retrieve folder (which is typical media item with different type), despite of the required returned type. I usually use TypedMedia to be able to operate on strongly typed object and preview properties in Visual Studio.
If we create macro properly and insert it on the template using code like this (with proper folder ID):
#Umbraco.RenderMacro("Test", new { mediaId="1082" })
we should see a list of images from this folder (all of them at that moment).
The final part is almost the same as you previously did it, but we need to adjust it a little bit. My final code and suggestion is below:
#inherits Umbraco.Web.Macros.PartialViewMacroPage
#{
var folderId = Model.MacroParameters["mediaId"];
if (folderId != null)
{
var media = Umbraco.TypedMedia(folderId);
var rand = new Random();
var imagesInFolder = media.Children("Image");
if(imagesInFolder.Any()) {
var pick = imagesInFolder.ElementAt(rand.Next(0, imagesInFolder.Count()));
if (pick != null)
{
<img src="#pick.GetCropUrl()" alt="#pick.Name" />
}
}
}
}
Let me know if it solved your problem :)

MVC ExtractAssociatedIcon show icon in view

I would like to display a file icon in one of my views.
#System.Drawing.Icon.ExtractAssociatedIcon(#"C:/Users/User1/Desktop/test.txt")
Shouldn't this display the icon? Do I need a img tag or something else?
Thanks
You cannot just have the file contents on the browser. You will need to use an <img> tag and have the server return the file stream:
Quick disclaimer: I do not have VS with me, so this is just pseudo-code:
public FileResult Icon()
{
var stream = System.Drawing.Icon.ExtractAssociatedIcon(#"C:/Users/User1/Desktop/test.txt")
return new FileStreamResult(stream, "image/png");
}
Then, just reference the action method:
<img src="/MyController/Icon">

Basic scenario of navigating to another page based on a row clicked in a table

I have a table with a bunch of items. Each row can be clicked (on any columns in this row) and navigate to another page based on the clicked row. I have a javascript file attached to this page where I manage events (clicked row, ...).
In my ASP.NET MVC solution, I would like to choose a goo way to manage this scenario.
Below is the one I think:
My view:
<table>
<tbody>
#foreach (var item in Model)
{
<tr data-url="#Url.Action("General", "Transport", new { transportID = item.TransportID })">
<td>aaaa</td>
<td>bbbb</td>
<td>cccc</td>
</tr>
}
</tbody>
</table>
My js file:
$("table.search-transport tbody tr td:not(:first-child)").live("click", function () {
var url = $(this).parents('tr').data('url');
window.location.href = url;
});
Because we cannot inject server code inside javascript files, I inject the url directly inside each rows inside my view. When a row is clicked, I get this "specific" url and navigate to it from my javascript file.
I would like to know if this solution is steady enough in an MVC project.
Following up from the comments, Nikola is right in saying that this does not impact the usage of the ASP.NET MVC framework. Injecting the URL into a data field in your case is the only option as far as I can see it (but I am open to other suggestions).
For the js part, I would use event delegation to avoid attaching events to every single cell:
$("table.search-transport tbody tr").on("click", "td:not(:first-child)", function () {
var url = $(this).parents('tr').data('url');
// also: $(this).parent().data('url'); will work...
window.location.href = url;
});
This will attach the event to each row but fire only when you click on a td which is not the first child. Alternatively, you could attach the whole event once to the table, thus also having the option of adding rows dynamically and still having the event attached; like this:
$("table.search-transport").on("click", "tr td:not(:first-child)", function () {
[...]
});

Conditional link in Razor

I have some tabs, and I want to say "if they are currently on the page that this tab refers to, make this a span. Otherwise, make this a link." In pseudo-razor, that would look like this:
#if(CurrentlyOnThisPage) {
<span>
} else {
<a>
}
Tab Content
#if(CurrentlyOnThisPage){
</span>
} else {
</a>
}
Razor (correctly) notes that I'm not closing my beginning tags, and so has trouble parsing this syntax. If the tab content was small, I could use Html.ActionLink, but I've got a few lines of stuff and I'd like to keep the benefits of the HTML editor rather than putting it all into a string. Is there any way to do this?
You can write the tags as literal text to prevent Razor from parsing them:
#:<span>
How about something like this?
#{
var linkOrSpan= CurrentlyOnThisPage ? "span" : "a";
}
<#linkOrSpan><text>Tab Content</text></#linkOrSpan>
No errors about closing tags with this.
Looks a bit cleaner too ihmo.
HTH
Or just write it out explicitly:
#if(CurrentlyOnThisPage)
{
<span>tabcontent</span>
} else {
<a>tabcontent</a>
}

Resources