Umbraco: Get value from a content child property - umbraco

I'm creating a blog with the CMS Umbraco. To create a post i've in Umbraco's Content a Home where you have a Post as a child item.
When you create this Post you have a dropdown-picker for categories, I want to get the values from this categories dropdown-picker to my sidebar to display all categories avaliable on the blog.
I want my dropdownpickers-value on my sidebar. What's the easiest approach?
Thanks.

I think this is what you are looking for:
UmbracoHelper - GetPreValues
Regards
Craig

GetPreValues was the answer, Thanks. This worked out for me.
#foreach (var categoryPrevalue in ApplicationContext.Services.DataTypeService.GetPreValuesByDataTypeId(YourDatatypeID).ToList())
{
<a href="#">
<span>#categoryPrevalue</span>
</a>
}

There are lots of ways to handle categories, but one of the best ways I have found is to create a Common Area from Root with a categories child within. Within categories you add all the category children.
- Common Area - Categories - Category
Instead of creating the categories as prevalue dropdown they are exposed as objects that are easily editted.
To show these categories on your template use a bit of Umbraco Helper Magic.
#{
var blogCategories = Umbraco.TypedContentAtXPath("//categories");
}
This will yeald an IPublishedContent object that you can iterate over to get the category name
foreach(var item in blogCategories.Where("Visible")
{
<li>#item.Name</li>
}

Related

Is it possible to access properties on dynamic composition models in Umbraco?

I have a few different styles/templates on my site. These templates are all used for compositions all over my site. Here's an example of my Document Types:
Layouts (folder)
Style 1
Style 2
Style 3
Products (folder)
ProductsPage
Product
News (folder)
NewsOverview
NewsPage
That's basically what it looks like. All of these have templates except for Product and NewsPage, but they have Style X as compositions. Here is what my content nodes looks like:
Home
Products
Product 1 (Style 2)
Product 2 (Style 3)
Product 3 (Style 2)
Product 4 (Style 1)
News
Article 1 (Style 1)
Article 2 (Style 3)
and so on. You get the point? The Style X document types are all compositions, so I don't have to style the same page over and over again, but I can still create any style of page I want.
Now, on my parent (for example NewsOverview), I would like to access the properties of the children. Inside the NewsOverview template file, I would then have to do this:
#foreach(var article in Model.Content.Children) {
dynamic image = article;
<img src="#image.OverviewImage[0].Url" />
<p>#article.GetPropertyValue("overviewTitle")</p>
}
I cannot access the properties without using strings or casting to dynamic (basically), although my models are set to Dll and I usually can do Model.Content.PROPERTY with intellisense and so on.
How can I achieve this? How can I access the properties without using dynamic? I understand that the children aren't necessarily all the same, but all my styled pages contains the same properties, they're just arranged differently in the template.
There's a method called Children<T>() that gets all the child documents of a certain type and can thus safely be cast in a foreach:
#foreach(Article article in Model.Content.Children<Article>()) {
<img src="#article.OverviewImage.First().Url" />
<p>#article.OverviewTitle</p>
}
You'll probably want to add some logic around article.OverviewImage.First() as if there is no value for OverviewImage it will throw a null reference exception.
Have you added your parent model to the template?:
#inherits UmbracoViewPage<ContentModels.Product>
#using ContentModels = Umbraco.Web.PublishedContentModels;
You probably need to cast the children to the specific type:
#using ContentModels = Umbraco.Web.PublishedContentModels;
#foreach (var article in Model.Content.Children.Select(child => new ContentModels.NewsPage(child)) {
<img src="#article .OverviewImage.First().Url" />
<p>#article.OverviewTitle</p>
}
.Children() just gets children of type IPublishedContent, because the ModelsBuilder has no idea which types of documents can exist under the current page.

Displaying a list(array) in a particular order in ASP.NET MVC

I am trying to display a list of items in ASP.NET MVC view using Razor's foreach helper:
#foreach(var item in items)
{
<div class="...">#item.SomeProp </div>
}
The items is a list of objects with particular properties. I need to display them in a particular order. What I am currently doing is I have property called Order in the object and then manually assign value to it according to some order but was wondering if there are better solutions.
Thanks
It might be the same as what you mentioned with your Order property, but the last time I needed to do this, I added a property to my Model object that was readonly. Something like this (obviously pseudocode):
public List<whateverObjectGoesHere> OrderedList
{
get
{
//Sort list somehow
return orderedList;
}
}

I am looking for advanced resources on customizing MVC3 editor templates

I have been struggling with my customization of EditorForModel and the naming of HTML elements emitted by my code and the built-in MVC3 helpers. My code is very simple, and is clearly missing some subtleties, like naming the the rendered elements properly.
I am looking for advanced resources that can help me hone this area of my current development, especially with a view to subdividing a main view model across smaller sub-models, so that I can apply say three EditorForModel calls in one view, to split generated model editors across form columns or tab pages.
My current 'override' of the default EditorForModel template is as follows:
#{
// TODO Filtering for subsets of model without having to bind separate models.
var properties = ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !pm.IsComplexType && !ViewData.TemplateInfo.Visited(pm));
}
<fieldset>
<legend>#ViewData.ModelMetadata.DisplayName</legend>
<ul class="form-column">
#foreach (var prop in properties)
{
<li>
#{
if (prop.HideSurroundingHtml)
{
#Html.Editor(prop.DisplayName ?? prop.PropertyName)
}
else
{
#Html.Label(prop.PropertyName, (prop.IsRequired ? "* " : "") + (prop.DisplayName ?? prop.PropertyName))
#Html.Editor(prop.PropertyName)
}
}
</li>
}
</ul>
</fieldset>
I have copied and modified this code from the Object.ascx example template on this article on Brad Wilson's blog. What resources can I consult to enrich this to cater for as many scenarios as possible, in as rich a manner as possible?
Your template seems pretty good for a very generic editor. If I understand your question properly, you're looking for more ways to break up and filter your model properties.
One way to filter the model into subsets without having to create submodels would be to use attributes. You could create as many attributes as you want, and have them implement IMetadataAware. There you could add arbitrary properties to the ModelMetadata.AdditionalValues property bag, and have your editor templates inspect those values.
Alternatively you could implement your own custom ModelMetadataProvider that returns a custom ModelMetadata object that had whatever properties you wanted.
Either would allow you to simply annotate your model to define filter behavior.
Both these methods are described by who else, Brad Wilson, in this blog post.

EF4 + Poco = Problem Updating many to many relationships

Let me explain the whole context:
I'm using ASP.NET MVC 2, EF4 (POCO).
I trying to do a generic repository for my app.
I'm having problem on updating a many to many relationship.
I have an item that is related to other by a many to many table. In the View, the user picks the desired Categories, and send just the chosen id's to the Controller.
Then, the Controller queries the Category Repository, adding it to the main item:
item.Categories.Add(CategoriesRepository.Single(id);
But, when I go the Repository and try to save like this:
Entities.ApplyCurrentValues(entity);
Context.SaveChanges();
But, the state of my entity is Added.
Then, I Cannot save my entity :(.
How can I solve this problem?
Thanks for your answers.
I have in the View, the following code:
<%= Html.CheckBoxList("Categories", ((IEnumerable<Categories>)ViewData["Categories"]).ToDictionary(c => c.ID.ToString(), c => c.Name)
, Model.Categories.ToDictionary(c => c.ID.ToString(),c => c.Name )) %>
Where CheckBoxList is a HTMLHelper.
Im putting the ids as values in the View, because I dont know other way to put and then get this information from the View.
How can I use the ObjectStateManager.ChangeRelationshipState method?
Like this? :
itemRepository.Db.ObjectStateManager.ChangeRelationshipState(item, item.Categories, "Categories", System.Data.EntityState.Modified);
I trying in this way, but it returns error.
Help! lol
You've got a few problems.
1) ApplyCurrentValues only works for scalar-properties. Since your trying to add a Category to the Categories navigational property on Item, this will not work.
2) You say this:
the user picks the desired Categories, and send just the chosen id's to the Controller.
How can your Controller accept a bunch of id's? How is this model binding done? We need more info on how your View is bound to your model, what's being passed to the action method. But it sounds like you need to redesign this particular View with the help of a ViewModel.
3) Change tracking with POCO's in MVC is a royal pain in the butt. In your scenario, you'll need to use ObjectStateManager.ChangeRelationshipState to manually set the Categories relationship to **Modified.
Honesty though, it's more pain than it's worth. I went through this same problem.
Cop it on the chin - go grab the entity first and use Controller.UpdateModel:
[HttpPost]
public ActionResult Item(Item item)
{
// get the existing item
var existingItem = ItemRepository.Single(item.Id);
// use MVC to update the model, including navigational properties
UpdateModel(existingItem);
// save changes.
Context.SaveChanges();
}

How to use DisplayForModel() to show a list of Customers?

Normally we use DisplayForModel or EditorForModel to display and edit a single Customer object, respectively.
How to display a list of Customers using these templating scheme?
Assuming you have a collection of customers in your view model
public class MyViewModel
{
public IEnumerable<Customer> Customers { get; set; }
}
you could use the following in your view:
#Html.DisplayFor(x => x.Customers)
and then in the editor/display template (~/Views/Home/DisplayTemplates/Customer.cshtml or ~/Views/Shared/DisplayTemplates/Customer.cshtml):
#model AppName.Model.Customer
<div>#Model.Name</div>
The Customer partial will be then rendered for each element of the customers collection of your main model. The important thing is the naming convention: the partial should be situated in a DisplayTemplates subfolder and called the same as the collection type (Customer).
How about following Haack's tutorial ?
As great as this feature is, there is
one template that’s conspicuously
missing. ASP.NET MVC does not include
a template for displaying a list of
objects in a tabular format.
Earlier
today, ScottGu forwarded an email from
Daniel Manes (what?! no blog! ;) with
a question on how to accomplish this.
Daniel had much of it implemented, but
was trying to get over the last
hurdle. With Brad’s help, I was able
to give him a boost over that hurdle.
Let’s walk through the scenario.

Resources