Friday, June 22, 2012

Problem with setting field's internal name with AddFieldAsXml


If you are trying to Add fields to a SharePoint list using AddFieldAsXml method with Client Side Object model you might be doing something as below -

using (ClientContext ctx = new ClientContext("http://opc-ad-devspw1/sites/devenf/wb2/%22))
{
       Web web = ctx.Web;
       FieldCollection flds = web.Lists.GetByTitle("MyList").Fields;
       ctx.Load(flds);
                flds.AddFieldAsXml("<Field DisplayName='My Field' Name='MyField' Type='Boolean' />", true, AddFieldOptions.AddFieldToDefaultView);
                ctx.ExecuteQuery();
}

I ran into a problem were my field was getting added, but my internal name was being set to “My_x0020_Field” discarding my Name property.  Finally, after little bit of research I found out that to set field’s internal name with AddFieldAsXml you need to use AddFieldOptions.AddFieldInternalNameHint. 

check here - http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spaddfieldoptions.aspx

flds.AddFieldAsXml("<Field DisplayName='My Field' Name='MyField' Type='Boolean' />", true, AddFieldOptions.AddFieldInternalNameHint);

Using AddFieldInternalNameHint fixed my problem and it's not a bug.