Thursday, September 20, 2007

How to get display form URL of a list item

Often, developing custom web parts, you may want to render a link to a list item. In SharePoint 2.0 you could get a list in which a list item is stored, and just create a link pointing to its display form, providing ID of a list item as a parameter in request query string. In SharePoint 3.0 this task is a bit more complicated, because now developers can specify custom URL of edit/new/display forms for each content type. If custom URL is not specified, content type uses appropriate form of a list. To make things even more complicated, URL of a custom form can point to application pages (stored in _layouts) as well. In this case, you should pass not only ID of an item as a parameter in request query string, but also GUID of a list, in which this item is stored. Otherwise, application page can not determine in which list it should search for an item with specified ID. So, if you need to get a complete URL of item’s display form, you may code something like:

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

SPListItem item = GetItem(); // some code to get a list item
SPList list = item.ParentList;
SPWeb web = list.ParentWeb;

string webUrl = web.Url;
string dispUrl = item.ContentType.DisplayFormUrl;
if(dispUrl == "")
dispUrl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
bool isLayouts = dispUrl.StartsWith("_layouts/",StringComparison.CurrentCultureIgnoreCase);
dispUrl = String.Format("{0}/{1}?ID={2}",webUrl,dispUrl,item.ID);
if(isLayouts)
dispUrl = String.Format("{0}&List={1}",dispUrl,SPEncode.UrlEncode(list.ID+""));
As a result, you will get full display form URL of a list item. However, if you want to get just a “clickable” URL, to place in some hyperlink, you don’t need to write so much code. You may create URL by using only an address of a list display form. SharePoint will analyze provided ID of an item then and redirect your request to appropriate page. You may code just:

SPListItem item = GetItem(); // some code to get a list item
SPList list = item.ParentList;
SPWeb web = list.ParentWeb;
string webUrl = web.Url;
string dispUrl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;;
dispUrl = String.Format("{0}/{1}?ID={2}",webUrl,dispUrl,item.ID);

53 comments:

Anonymous said...

Excellent tip - many thanks.

Tomek said...

Works great, thanks :)

Део said...

Спасибо, пригодилось, полезно

GATzilla said...

In some cases the line

string dispUrl = item.ContentType.DisplayFormUrl;

can throw a NullReferenceException because the ContentType property of a list item can be null. So this line should be written like

string dispUrl = item.ContentType == null ? String.Empty : item.ContentType.DisplayFormUrl;

Anonymous said...

порно онлайн видео молодые http://free-3x.com/ молодежное видео онлайн порно free-3x.com/ малолетка [url=http://free-3x.com/]free-3x.com[/url]

Anonymous said...

lesbian ass licking movie lesbian cheaters indian lesbian girls ellen hilburn lesbian incredibles lesbians free ten minute videos lesbian beautiful lesbians kissing

Anonymous said...

Your blog keeps getting better and better! Your older articles are not as good as newer ones you have a lot more creativity and originality now keep it up!

Anonymous said...

topic14, [url=http://www.chop.edu/forum/user/profile/8207.page]order klonopin no prescription[/url], ;-( izf, http://www.chop.edu/forum/user/profile/8207.page buy klonopin without prescription :-), [url=http://www.chop.edu/forum/user/profile/8208.page]purchase xanax 2mg[/url], ;-( fxq, http://www.chop.edu/forum/user/profile/8208.page order xanax 2mg ;-(, [url=http://forum.cprs.ca/default.aspx?g=posts&m=6]order adipex online[/url], :-( awn, http://forum.cprs.ca/default.aspx?g=posts&m=6 order adipex ;-(, [url=http://forum.cprs.ca/default.aspx?g=posts&m=7]cheap alprazolam[/url], :-) ttk, http://forum.cprs.ca/default.aspx?g=posts&m=7 buy alprazolam without prescription ;-(, [url=http://forum.cprs.ca/default.aspx?g=posts&m=8]order ambien no prescription[/url], :-( gcr, http://forum.cprs.ca/default.aspx?g=posts&m=8 ambien no prescription :-)

Anonymous said...

[color=#6699cc]
Как жизнь? Может-быть... есть cупер мысль по[url=http://www.pi7.ru] видео[/url] порталу Думаю вам понравится

[url=http://www.pi7.ru]собачий член начал [/url]
aнекдот для разнообразия :)

Девушка хвастается подруге:
- Я вчера такого парня встретила! ! ! ! У него такой член, такой член! ! У мнея даже в голове не укладывается!

Я 9 часв блуждала по ести, пока не вышела на вш форму! Думаю, я здесь останусь надолго!
прошу прощения за опнечатки.... очень маленькаея клавиатура у PDA!

[/color]

Anonymous said...

Hello,

I keep coming to this website[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url]sharepointex.blogspot.com really contains lot of useful information. Frankly speaking we really do not pay attention towards our health. In plain english I must warn you that, you are not serious about your health. Recent Research presents that closely 60% of all United States grownups are either fat or overweight[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url] Hence if you're one of these people, you're not alone. Its true that we all can't be like Brad Pitt, Angelina Jolie, Megan Fox, and have sexy and perfect six pack abs. Now next question is how you can achive quick weight loss? [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss[/url] is not like piece of cake. If you improve some of your daily diet habbits then, its like piece of cake to quickly lose weight.

About me: I am blogger of [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss tips[/url]. I am also health trainer who can help you lose weight quickly. If you do not want to go under painful training program than you may also try [url=http://www.weightrapidloss.com/acai-berry-for-quick-weight-loss]Acai Berry[/url] or [url=http://www.weightrapidloss.com/colon-cleanse-for-weight-loss]Colon Cleansing[/url] for effective weight loss.

Anonymous said...

Hello. And Bye.

Anonymous said...

Howdy,

Do you guys watch movies in theater or on internet? I use to rent DVD movies from [b]Netflix.com[/b]. Recently I discovered that we can watch all new movies on internet on day, they are released. So why should I spend money on renting movies??? So, can you guys please tell me where I can [url=http://www.watchhotmoviesfree.com]watch latest movie Despicable Me 2010[/url] for free?? I have searched [url=http://www.watchhotmoviesfree.com]Youtube.com[/url], [url=http://www.watchhotmoviesfree.com]Dailymotion.com[/url], [url=http://www.watchhotmoviesfree.com]Megavideo.com[/url] but, Could not find a good working link. If you know any working link please share it with me.


Thanks

buy viagra said...

hi, I like this information, I really enjoyed this post!
viagra online
generic viagra

Anonymous said...

http://auto-financing.co.cc

Anonymous said...

http://friends.rambler.ru/fesbatije@rambler.ru
http://friends.rambler.ru/mushynede@rambler.ru
http://friends.rambler.ru/debackhighpa@rambler.ru
http://friends.rambler.ru/fluterbipurp@rambler.ru
http://friends.rambler.ru/semmesisli@rambler.ru

Anonymous said...

http://friends.rambler.ru/ymintinomb@rambler.ru
http://friends.rambler.ru/stagnewnibo@rambler.ru
http://friends.rambler.ru/mipoboolo@rambler.ru
http://friends.rambler.ru/smellaispiltext@rambler.ru
http://friends.rambler.ru/fluterbipurp@rambler.ru

Anonymous said...

http://alltits.com.nu/big-tits-in-thong.html
http://alltits.com.nu/asian-banana-tits.html
http://beaudodoti.szm.com/lotion-anal-sex.html
http://esexalon.szm.com/brothers-penis.html
http://adultbot.szm.com/wife-sex-toys.html

Anonymous said...

http://oculresmie.szm.com/black-haired-pornstar.html
http://upskirtq.com.nu/mandy-moore-upskirt.html
http://oculresmie.szm.com/highest-rated-pornstar.html
http://oculresmie.szm.com/pornstar-scope.html
http://upskirtq.com.nu/kate-bosworth-upskirt.html

Anonymous said...

http://beaudodoti.szm.com/monica-bellucci-hot-sex.html
http://alltits.com.nu/huge-tits-jpg.html
http://shemale.com.nu/all-black-shemale.html
http://alltits.com.nu/tits-fighting.html
http://alltits.com.nu/bitches-big-tits.html

Anonymous said...

yes http://futbrosi.ru/

Anonymous said...

Viagra controindicazioni acquisto - http://turbovdubs.com/forum/index.php/topic,202182.new.html#new trova viagra di Modena.
Server emule la ricetta per il viagra - http://michaeljacksonsighted.com/forum/index.php?topic=79748.new#new offerta comprare viagra Firenze (Toscana).
Viagra vista per - http://forum.manifestationsofadream.com/index.php?topic=77751.new#new definizione del viagra Andria.
Farmacie comprare viagra - http://www.parts.tu1.ru/modules.php?name=Forums&file=viewtopic&p=254#254 acquisto viagra lombardia Cesena.
Benefici viagra effetti collaterali - http://smf.godmorgen.org/index.php?topic=87084.new#new formula canadian pharmacy viagra Offerte Lavoro.
Lampada viagra in farmacia - http://electronics-forum.com/index.php?topic=43069.new#new viagra pomata la disfunzione erettile ForlРј-Cesena.
Indicazioni viagra effetti collaterali - http://www.mytweetgold.com/forums/index.php?topic=35508.new#new cialis viagra confronto levitra Salerno.
Cerco viagra - http://politomics.org/forum/index.php?topic=320439.new#new viagra o levitra eiaculazione precoce Firenze.
Viagra scatole - http://realtyproforum.com/index.php?topic=43055.new#new eolica naturale al viagra Lodi (Lombardia).
Allegra massimei viagra - http://www.anti-age-bio.com/forum/viewtopic.php?f=3&t=10947 vescica e viagra Arezzo.
Viagra diplegia - http://www.loxent.com/index.php?topic=12587.new#new comprare il viagra senza ricetta Reggio Calabria.
Viagra prezzo erboristeria - http://alamoareadiving.com/smf/index.php?topic=189712.new#new scherzi a parte viagra Lecco (Lombardia).
Alcol e viagra anche - http://foro.nefftarodas.es/index.php?topic=7528.new#new simil viagra Emilia-Romagna.
Viagra aeronautica - http://www.torontoismine.com/forum/viewtopic.php?f=2&t=439775 viagra senza ricetta in svizzera effetti collaterali Crotone (Calabria).

Anonymous said...

Тебе изменила жена? Тогда тебе на http://drochatvse.ru/ Размести ее фото и видео На нашем портале более 100000 пользователей ежедневно просматривают фото и видео жен изменщиц. Сочувствуют мужьям, наслаждаются эротическим видео, курьезными случаями, задорным порно, веселыми приключениями любовников.
Ппользователи клуба могут оставлять свои комментарии, drochatvse.ru

Anonymous said...

Здравствуйте. Продаеться партнерская программа http://cartbucks.ru/ многофункциональная, платники в основном сайты знакомств. Работает уже месяц,
все нормально, функционирует конверт отличный. Раскрутка пойдет быстро. Программа идет целиком с 10 платниками. Смотреть cartbucks.ru Цена договорная
с торгом. Кто желает пишите тикеты, либо на мыло плиз инфу afilliator@gmail.com Команда занята другим проектом, пишите договоримся (cartbucks.ru)

Anonymous said...

It is captivating to understand this theory and area of its appendix in gambling.
That I know on every side it - it concerns statistics, is applied to the settlement of the nonlinear equations.
Very much the exegesis to the problem decision (representing cultivate at this very moment anybody so plainly illustrate nothing a smog) interests:
There is a teleshow - the virtuoso and the leader.
There are three doors. Behind one of them the champion, behind two others is not present.
The chief offers a select to the player that accordingly chooses any of 3 doors (their probabilities are fifty-fifty).
After the choice is made, the leader who knows where lies a superior, opens whole of those doors that are not chosen away the performer and shows that there the loot is not present. Also suggests the competitor to select from time to time again already between 2 doors.
Beyond consideration - how to arrive to the player? (In a outset it is specified that it is indispensable to replace a option, the odds of a receipts behind a door on which was specified nearby the player who is doing not direct = 66.7 %.
Very much I attend to in compensation councils or at least references where to look.
For more intersting look http://www.obu.edu/centers/images/index.html

Anonymous said...

НИУ-ИБИС - создание, продвижение, аренда и поддержка сайтов. http://niu-ibis.ru Зайдите на наш сайт и рассчитайте самостоятельно стоимость всех Ваших затрат, а мы Вам сделаем еще скидку!!!

Anonymous said...

Amazon launched two new Kindle e-readers priced at $139 and $189 late Wednesday, with the cheaper version a Wi-Fi-only e-reader and $10 less than the Wi-Fi-only Nook.
[url=http://www.computerworld.com/s/article/9179853/Amazon_launches_two_new_Kindles_one_with_Wi_Fi_only]ComputerWorld[/url]
http://www.computerworld.com/

Anonymous said...

Сайт [url=kmdd.ru]Мебель для дома[/url] предлагает Вам узнать все, что касается современой мебели.

Anonymous said...

Наткнулся сайт в интеренете. Сразу впоследствии регистрации дают [b]халявные 100$[/b].
Я уже получил. Спешите и Вы http://www.bidbroker.org

Anonymous said...

http://helicopterlife.net/fourms/index.php?topic=26015.new#new older white milf http://barishoes.com/forum/index.php?topic=17552.new#new milf bra panties http://soundsintheattic.com/boards/index.php?topic=17522.new#new milf bjs http://rap-ks.ru/forum/index.php?topic=89775.new#new hot milf pic http://www.ran-hot.com/webboard/index.php?topic=5341.new#new amateur naked milf

Anonymous said...

Шины и диски на любой вкус shinway ru. Я заказал шины goodyear ultragrip-500, вопервых оказалась дешевле чем в аналогичных магазинах, а вовторых доставили очень быстро несмотря на то, что я живу в Питере, а магазин в Новосибирске. Всем рекомендую очень хороший [url=http://www.shinway.ru/]интнрнет-магазин[/url].

Anonymous said...

Конкурс на лучшую иконку для сайта (favicon) - условия http://www.eromania3d.ru/myblog-1

Anonymous said...

Наши сайты:
Bayswater Inn Repiska Aladin Resort Hillside Su Hotel Tanjung Aru Resort Ephesia Holiday Beach Club Marina All Suites Italia Hotel Финляндия Ferrari 360 Modena 3.4л 79100 2004 Daihatsu Feroza 61993 Buick Roadmaster 1994 Mini Cooper S 1998 Blonell Mitsubishi Challenger 27800 1992 Blonell TF 2000 6 80600 2002 Ferrari 575 M Maranello 2.6 15600 1994 Chery Tiggo 7.5 55400 1999 Dallas FUN 2.5 2005 Concordia Celes Hotel Berke Ranch Hotel Carlisle Bay Koenigsegg CC $39700 2009 Ford Orion $55600 1991 Coggiola T Rex 7.5л 2000

Anonymous said...

[b][url=http://0503500010.com] Escort Agency[/url][/b]
Barby-Girls is an Escort Agency providing female escorts services.
We have a full portfolio of the most elegant and stunning girls that you ever likely to meet in Israel.

http://0503500010.com

Anonymous said...

Качествено и в короткие сроки наши специалисты выполняют [url=http://www.engineersystems.ru/]проекты по внутреннему и внешнему электроснабжению[/url]
торговых комплексов, магазинов, квартир, дачных участков.
Лицензия СРО на проектирование.
Выезд на обследование и предварительные переговоры бесплатен.

Anonymous said...

Профессиональный хостинг сайтов от 30 руб. в месяц 500 мб http://libertyhost.ru

Anonymous said...

Профессиональный хостинг сайтов от 30 руб. в месяц 500 мб http://libertyhost.ru

Anonymous said...

Скачать

Быстро скачать

Скачать очень быстро

Скачать одной ссылкой

Скачать торрентом

Самая высокая скорость скачивания

Anonymous said...

Вот последние кинофильмы что я нашла в сети из рабочих

Anonymous said...

Журнальный столик квадратный,на колесах, марки "ДЕКОРЛИТ " изготовлен из литьевого искусственного камня.
Цвета опор на выбор:
- для Черного мрамора и Черного с золотом - черная фактурная кожа
- для Бежевого мрамора и Белого с серым и какао - белая фактурная кожа.
Цвет столешницы на выбор.
Низкие ценам - http://www.eyus.ru/category_3.html

Anonymous said...

Журнальный столик квадратный,на колесах, марки "ДЕКОРЛИТ " изготовлен из литьевого искусственного камня.
Цвета опор на выбор:
- для Черного мрамора и Черного с золотом - черная фактурная кожа
- для Бежевого мрамора и Белого с серым и какао - белая фактурная кожа.
Цвет столешницы на выбор.
Низкие ценам - http://www.eyus.ru/category_3.html

Anonymous said...

песни скачать
[url=http://remuz.ru/162-тимати.html]слушать тимати[/url]
бесплатная музыка без регистрации
[url=http://remuz.ru/365-ранетки.html]mp3 ранетки[/url]

Anonymous said...

goqr nxnoq Large Tits sooher w in m tgz

Anonymous said...

jgke kpinq [URL=http://www.bigtits234.com]bigtits234[/URL] iyqscz z wb a lpc

Anonymous said...

Все хорошее когда-нибудь заканчивается. Это высказывание, к сожалению, относится и к эрекции. Эрекция прекращается почти сразу же после эякуляции, потому что эякуляция является сигналом к прекращению выработки циклической АМФ. Но даже прежде, чем ваша эрекция прекратится сама собой из-за эякуляции в половом члене происходит серия химических реакций, направленных на то, чтобы защитить орган от «переутомления».
[url=http://webshop.cx.cc/zakazat-viagru.html]Тадасип[/url]
[url=http://webshop.cx.cc/viagra-pfayzer.html]Силденафила[/url]
[url=http://webshop.cx.cc/viagra-deystvuet.html]Сиалис Левитра[/url]
Врачи утверждают, что преждевременной эякуляцией страдают мужчины всех возрастов, вне зависимости от их деятельности или других явных причин. Преждевременное семяизвержение в данном случае - это не результат чрезмерного сексуального перевозбуждения, а настоящее заболевание.

Anonymous said...

Sorry for the stupid question. What is the best search engine http://google.com or http://yahoo.com?

Anonymous said...

Всего самого наилучшего
http://nashmir.com.ua/engine/redirect.php?url=http://ufpk.kiev.ua

Anonymous said...

Urteter nuytre: http://dietavor.001webs.com

Anonymous said...

Растаможка Киев, Одесса
Консультации ВЭД
Дима Литейный
logisticskiev7@yandex.ru
+38 093 318 1567

Anonymous said...

Hey just becoming a member, glad to be in! I'm glad to be right here finally, heading to submit since I've been studying a extended time.

I've been concerned in some other forums and have identified this place to have very much more effective written content, so it helps make sense to ultimately publish!

BTW where is the option to change the little picture thingy like some people have, I like it but can't figure it out haha

Anonymous said...

Hey just joining, glad to be here! I'm glad to be here as a final point, heading to submit considering that I've been reading through a prolonged time.

I've been concerned in some other forums and have found this place to have much much better articles, so it tends to make sense to finally post!

BTW, what can I do to change the little picture thingy like some people have, I like it but can't figure it out haha

Anonymous said...

Sorry for the stupid question. What is the best search engine http://google.com or http://yahoo.com?

Anonymous said...

What i discover tough is to discover a weblog that can capture me for a minute however your blog is different. Bravo. pocketbooks handbags purses durham| как появилась фамилия закроенко| черная майка на заказ| elsewhere as best they might
http://s1.shard.jp/campskat/ymca-golf-for-life-camp.html Click Here

Anonymous said...

http://dematom.com/images/2008/11/19/1062-hoziain_iskrenne_sovetuiu_ne_zagliadyvai_v_kladovku.jpg





_________________
Когда труд — удовольствие, жизнь — хороша! Когда труд — обязанность, жизнь — рабство!