How to get Sharepoint User object from the "AssignedTo" field using client side object model?

user90147 picture user90147 · Aug 1, 2010 · Viewed 37.6k times · Source

I am using managed client side object model in sharepoint 2010. And I want to get loginaName of the AssignedTo user in Task list.

In server side object model I use SPFieldUserValue.User.LoginName to get this property but in client side object model FieldUserValue.User does not exists.

How can I resolve this situation ?

Thanks

Answer

ekhanna picture ekhanna · Jun 10, 2011

Here is the code for that. I've taken an example of AssignedTo field from Task list. I hope that helps.

    public static User GetUserFromAssignedToField(string siteUrl)
    {
        // create site context
        ClientContext ctx = new ClientContext(siteUrl);

        // create web object
        Web web = ctx.Web;
        ctx.Load(web);

        // get Tasks list
        List list = ctx.Web.Lists.GetByTitle("Tasks");
        ctx.Load(list);

        // get list item using Id e.g. updating first item in the list
        ListItem targetListItem = list.GetItemById(1);

        // Load only the assigned to field from the list item
        ctx.Load(targetListItem,
                         item => item["AssignedTo"]);
        ctx.ExecuteQuery();

        // create and cast the FieldUserValue from the value
        FieldUserValue fuv = (FieldUserValue)targetListItem["AssignedTo"];

        Console.WriteLine("Request succeeded. \n\n");
        Console.WriteLine("Retrieved user Id is: {0}", fuv.LookupId);
        Console.WriteLine("Retrieved login name is: {0}", fuv.LookupValue);

        User user = ctx.Web.EnsureUser(fuv.LookupValue);
        ctx.Load(user);
        ctx.ExecuteQuery();

        // display the user's email address.
        Consol.writeLine("User Email: " + user.Email);

        return user;
    }