SharePoint: Get content type, which is associated with the current request
In my project I’ve created custom display/edit/new forms for every usable list. The easiest way to get a SPContentType-instance, which is connected with the current Page, is a property SPContext.Current.ListItem.ContentType. Sometimes, I have to get the current content type inside OnInit-method of page lifecycle. If we edit or display an existed list item (edit/display-forms), we can do it easily, because SPContext.Current.ListItem is already defined and accessible. But, if we create a new list item (new-form), we don’t have a valid SPContext.Current.ListItem inside OnInit, because none is created yet. The following table demonstrates when (starting from what method of page lifecycle) SPContext.Current.ListItem.ContentType is already accessible:
Form |
Accessible starting from |
Edit | OnInit |
Display | OnInit |
New | OnLoad |
To get the current content type inside OnInit of New-form, at first we need to extract ContentTypeId from query-string of Page.Request, then having ContentTypeId we receive the instance of SPContentType. It should be noted that SPContext has an internal method GetContentTypeThroughQueryString, which provides SPCOntentType-instance based on id of content type in the query-string.
Of course, we can invoke this internal method through .Net Reflexion, but I prefer rewriting such methods, when it’s possible. So, now I have my own GetContentTypeThroughQueryString method:
protected SPContentType GetContentTypeThroughQueryString() { string cntTypeIdStr = HttpContext.Current.Request.QueryString["ContentTypeId"]; if (!string.IsNullOrEmpty(cntTypeIdStr)) { try { SPContentType spContentType = null; if (cntTypeIdStr.StartsWith("0x")) { SPContentTypeId contentTypeId = new SPContentTypeId(cntTypeIdStr); spContentType = SPContext.Current.List.ContentTypes[contentTypeId]; if (spContentType == null) spContentType = SPContext.Current.List.ContentTypes[SPContext.Current.List.ContentTypes.BestMatch(contentTypeId)]; } else { using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { int num = int.Parse(cntTypeIdStr, writer.FormatProvider); spContentType = SPContext.Current.List.ContentTypes[num]; } } return spContentType; } catch{} } return null; }
And the result method, that returns the current content type associated with the current request, is
protected SPContentType GetCurrentContentType() { if (SPContext.Current.ListItem != null && SPContext.Current.ListItem.ContentType != null) return SPContext.Current.ListItem.ContentType; // try to get content type through query string return GetContentTypeThroughQueryString(); }
GetCurrentContentType can be invoked inside any method of page lifecycle, even inside OnInit.