如何在FormFlow Bot Framework中首次错误尝试后验证并提供选项列表

时间:2017-05-13 11:41:25

标签: c# asp.net enums botframework

我正在尝试使用bot框架构建机器人,我想使用FormFlow从用户获取部门名称的字符串,如果用户输入错误的部门名称,我想验证并返回可供选择的选项列表< / p>

DepartmentName字符串:

[Prompt("What is your department name? {||}")]
 public string DepartmentName { get; set; }

Deaprtment name字段如下:

.Field(nameof(DepartmentName),

            validate: async (state, response) =>
            {
                var value = (string)response;
                var result = new ValidateResult() { IsValid = false, Feedback = "Department name is not valid"};
                if (Enum.GetNames(typeof(Department)).Any(x => x.ToLower() == value))
                {
                    result.IsValid = true;
                    result.Feedback = null;
                    result.Value = value;
                }
                return result;
            })

部门枚举如下:

public enum Department
{
    hr = 1,
    sales,
    marketing,
    development,
    qm
}

如果首次尝试出错,如何在枚举中提示用户列表? Thnaks

1 个答案:

答案 0 :(得分:2)

1)您只需将选项添加到反馈的末尾:

.Field(nameof(DepartmentName),
validate: (state, response) =>
{
    var value = (string)response;
    string[] departments = Enum.GetNames(typeof(Department)).ToArray();
    var feedback = $"Department name is not valid. Options:\n\n {String.Join("\n\n", departments)}";

    var result = new ValidateResult() { IsValid = false,                                            
                                        Feedback = feedback  };

    if (departments.Any(x => x.ToLower() == value))
    {
        result.IsValid = true;
        result.Feedback = null;
        result.Value = value;
    }
    return Task.FromResult<ValidateResult>(result);
});

2)您可以使用Choice类(通常用于消除歧义):

.Field(nameof(DepartmentName),
    validate: (state, response) =>
    {
        var value = (string)response;
        string[] departments = Enum.GetNames(typeof(Department)).ToArray();

        IEnumerable<Choice> choices = departments.Select(d => new Choice()
                {
                    Description = new DescribeAttribute(d, null, null, null, null),
                    Terms = new TermsAttribute() { Alternatives = new[] { d } },
                    Value = d
                }).ToArray();

        var result = new ValidateResult()
        {
            IsValid = false,
            Choices = choices,
            Feedback = "Department name is not valid."
        };

        if (departments.Any(x => x.ToLower() == value))
        {
            result.IsValid = true;
            result.Feedback = null;
            result.Value = value;
        }
        return Task.FromResult<ValidateResult>(result);
    });