将 CSOM 保存到选择字段时如何防止填写值
How to prevent fill in values when saving over CSOM to a choice field
我正在编写一些 ETL 代码以在外部系统和 SharePoint Online 之间移动数据。
我正在使用 nuget 包 Microsoft.SharePointOnline.CSOM 在 C# 中与 SP 通信。
我正在使用以下代码来更新我的字段值。
spListItem[fieldName] = "Test Value";
spListItem.Update();
spClientContext.ExecuteQuery();
我注意到 Choice 字段,如果我保存一个不存在的值,SharePoint 不会抱怨,只会添加该值,即使 Allow 'Fill-in' choices 设置为 NO。
SharePoint 中是否有验证功能?我看到了一些方法,例如 ValidateUpdateListItem,但它们似乎并没有满足我的需要。
您可以考虑在保存其值之前验证选择字段值,如下所示:
static class ListItemExtensions
{
public static bool TryValidateAndUpdateChoiceFieldValue(this ListItem item, string fieldName, string fieldValue)
{
var ctx = item.Context;
var field = item.ParentList.Fields.GetByInternalNameOrTitle(fieldName);
ctx.Load(field);
ctx.ExecuteQuery();
var choiceField = ctx.CastTo<FieldChoice>(field);
if (!choiceField.FillInChoice)
{
var allowedValues = choiceField.Choices;
if (!allowedValues.Contains(fieldValue))
{
return false;
}
}
item.Update();
return true;
}
}
In that case the ListItem
will be updated once the validation is
succeeded.
用法
using (var ctx = new ClientContext(webUri))
{
var list = ctx.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(itemId);
if(listItem.TryValidateAndUpdateChoiceFieldValue(fieldName,fieldValue))
ctx.ExecuteQuery();
}
我正在编写一些 ETL 代码以在外部系统和 SharePoint Online 之间移动数据。
我正在使用 nuget 包 Microsoft.SharePointOnline.CSOM 在 C# 中与 SP 通信。
我正在使用以下代码来更新我的字段值。
spListItem[fieldName] = "Test Value";
spListItem.Update();
spClientContext.ExecuteQuery();
我注意到 Choice 字段,如果我保存一个不存在的值,SharePoint 不会抱怨,只会添加该值,即使 Allow 'Fill-in' choices 设置为 NO。
SharePoint 中是否有验证功能?我看到了一些方法,例如 ValidateUpdateListItem,但它们似乎并没有满足我的需要。
您可以考虑在保存其值之前验证选择字段值,如下所示:
static class ListItemExtensions
{
public static bool TryValidateAndUpdateChoiceFieldValue(this ListItem item, string fieldName, string fieldValue)
{
var ctx = item.Context;
var field = item.ParentList.Fields.GetByInternalNameOrTitle(fieldName);
ctx.Load(field);
ctx.ExecuteQuery();
var choiceField = ctx.CastTo<FieldChoice>(field);
if (!choiceField.FillInChoice)
{
var allowedValues = choiceField.Choices;
if (!allowedValues.Contains(fieldValue))
{
return false;
}
}
item.Update();
return true;
}
}
In that case the
ListItem
will be updated once the validation is succeeded.
用法
using (var ctx = new ClientContext(webUri))
{
var list = ctx.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(itemId);
if(listItem.TryValidateAndUpdateChoiceFieldValue(fieldName,fieldValue))
ctx.ExecuteQuery();
}