Tuesday, January 10, 2012

!New tag in SharePoint 2010

SharePoint offers a !New tag for content that it considers to be new. It's a reasonably well-liked feature, it's out of the box, but how do you use it?

There are (at least) two things that you can do with it:

1) you can change what it means to be "new"
2) you can reuse the concept in a visual web part, or in other parts of your code

For the first item, changing what it means to be "new", you can either change the number of days for the new tag, or you can remove the new tag altogether.

For the second item, reusing the concept, you could use the new tag in an XSLT or data view web part, or you can use it in a visual web part.  Since I did not find out how to do the latter in any other blog, I'll detail it below:

First, in code behind, you can determine the number of days that an item is considered to be new:

        int daysToShowNew = SPContext.Current.Site.WebApplication.DaysToShowNewIndicator;

Then you can use this property to selectively show the new tag next to some content that you are displaying in your visual web part.  I used in a roll up web part that was showing announcements from a number of subsidiary sites, but it can be used anywhere.

It's somewhat a matter of coding style, but I like to separate the UI from the code, so my approach was to first create a property that can be accessed by the ASPX/ASCX:


        protected bool IsNew(string created)
       {
            DateTime createdDate = DateTime.Parse(created);
            return createdDate.Date.AddDays(daysToShowNew) > DateTime.Today;
        }

And then access it in my ASPX/ASCX, modifying the default HTML for this component:

<img class="ms-newgif" title="New" alt="New" src="/_layouts/1033/images/new.gif" visible="<%# IsNew(DataBinder.Eval(Container.DataItem,"Created").ToString()) %>" />







Labels: