Why Imam Rida (as) accepted position of Crown prince

حدثنا أحمد بن زياد الهمداني، قال: حدثنا علي بن إبراهيم بن هاشم، عن أبيه، عن الريان بن الصلت، قال: دخلت على علي بن موسى الرضا (عليه السلام)، فقلت له: يا بن رسول الله، إن الناس يقولون: إنك قبلت ولاية العهد مع إظهارك الزهد في الدنيا! فقال (عليه السلام): قد علم الله كراهتي لذلك، فلما خيرت بين قبول ذلك وبين القتل اخترت القبول على القتل، ويحهم أما علموا أن يوسف (عليه السلام) كان نبيا رسولا، فلما دفعته الضرورة إلى تولي خزائن العزيز قال له اجعلني على خزائن الأرض إني حفيظ عليم، ودفعتني الضرورة إلى قبول ذلك على إكراه وإجبار بعد الاشراف على الهلاك، على أني ما دخلت في هذا الامر إلا دخول خارج منه، فإلى الله المشتكى وهو المستعان

Narrated from al-Rayyan ibn al-Salt who said,

I visited Imam Ali ibn Musa al-Rida (عليه السلام) and said to Him, "O son of the Messenger of Allah! The people say: “You accepted the position of crown prince while you present yourself as being ascetic in this world."

So the Imam (عليه السلام) said, "Allah knows my dislike for that. When I was made to choose between accepting that and being killed, I chose to accept rather than to be killed. 

Woe to them! Do they not know that Yusuf (as) was a prophet and messenger, and yet when necessity compelled/forced him to take over the treasuries of the king, he said to him - "Appoint me over the treasuries of the land. Surely, I am a knowledgeable guardian." (12:55). 

And the necessity compelled me to accept that under compulsion, by force, at the verge of destruction. I did not enter this affair except as one who wants to leave it. So to Allah is the complaint and He is the Helper."

[Source: al-Amali of Shaykh Saduq, Page 130]