Using SPContext in Visual Web Part.
-
Friday, April 13, 2012 8:04 PM
Hi All,
I want to deploy a visual web part in a Web Part page, the Visual Web Part should be able to identify the current user who has logged in and also the site, web & web app details of where the web part is being deployed. I could do it with ease of using SPContext object., but the thing is i want to send the logged in and the above said details to an api (currently it is a class library type) which got the methods of accessing the UserProfile and returns the user details value. While debugging, i could note that it fetches the values from the specified api, but the web part page is not shown, instead it throws the error message as
"This control only works in the context of a SharePoint site. SPContext.GetContext failed to return an SPContext for the current request context."
In page load method of .ascx file, i have written as follows ::
using myprofileaccess; // referring the api (namespace of the dll)
private void Page_Load()
{
SPContext spctxtObj = SPContext.Current; // To get the logged in user and site where the web part is being deployed
MyProfileAccess servObj = new MyProfileAccess(); // object for the api call.
servObj.siteObj = spctxtObj.Site;
servObj.webAppObj = spctxtObj.Site.WebApplication;
servObj.webObj = spctxtObj.Web;
servObj.loggedInUser = spctxtObj.Web.CurrentUser.LoginName;
servObj.listObj = spctxtObj.List;
servObj.contentDBObj = spctxtObj.Site.WebApplication.ContentDatabases[0];
mydetails.text = servObj.UserDetails(); // value returned by the api is assigned to the text box.
}
Please, help me to avoid this error.. Thanx in Advance.
Naren.
- Edited by neran27 Friday, April 13, 2012 8:06 PM
All Replies
-
Saturday, April 14, 2012 2:07 AM
To answer your question, Need one more infor, So in your MyProfileAccess class , have you all the properties created with appropiate data types? then why are you setting data here at page load, capture details in the class and just use it here.All data assignment could have been done in your constructor itself...
And if your requirement say that you have to use SPcontext in your page load, you can use variables instead of setting it to the object of your class.
Ashish Ranjan (Please click "Marked As Answer" if a post solves your problem or "Vote As Helpful" if a post has been useful to you)
-
Saturday, April 14, 2012 3:54 PMHi Ashish, yes all the properties are there. The thing is the web part shuld identify the logged in user and passes the loginName, to the MyProfileAccess class, it will be opening the passed logged in user and fetches the values and returns back. the other details are needed for access logic.,
Naren.
-
Sunday, April 15, 2012 6:16 AM
Is servObj.UserDetails() using any kind of delegation with elevated rights?
MCPD, MCITP, MCTS

