3

我目前正在寻找一种方法来动态创建FormDialog数据库中预定义的值。换句话说,我的字段类型、提示和设置都存储在数据库中,我想要实现的是读取这些设置并动态构建适当的表单。

到目前为止,我尝试的是类似于以下内容。假设我有一个带有Name ( string) 和Age ( int) 字段的表单(FieldDefinition是我创建的用于存储字段参数的类,假设它们是从数据库中获取的)(代码被剥离只是为了说明这个想法)

    public static IForm<dynamic> BuildForm()
    {
        string FormMessage = "Welcome to demo contact form!";
        string CompletionMessage = "Thank your for your info. Our team will contact you as soon as possible.";

        var fields = new List<FieldDefinition>()
        {
            new FieldDefinition()
            {
                Name = "Name",
                FieldType = typeof(string),
                Prompts = new string[] { "What's your name?", "Please input your name" }
            },
            new FieldDefinition()
            {
                Name = "Age",
                FieldType = typeof(int),
                Prompts = new string[] { "What's your age?", "How old are you?" }
            }
        };



        var builder = new FormBuilder<dynamic>();
        builder.Message(FormMessage);

        foreach (var f in fields)
        {
            builder.Field(
                new FieldReflector<dynamic>(f.Name)
                .SetType(f.FieldType)
                );
        }

        builder.AddRemainingFields()
        .OnCompletion(async (context, order) => {
            var message = context.MakeMessage();
            message.Text = CompletionMessage;
            await context.PostAsync(message);
        });
        return builder.Build();
    }

所以这里有问题:

  1. 我想我可以使用一种dynamic类型。但是一个方法不能返回一个dynamic对象,因为它是在运行时确定的。因此,当我尝试使用以下内容构建表单时出现错误:

    dynamic values; var form = new FormDialog<dynamic>(values, ContactForm.BuildForm, FormOptions.PromptInStart, null);`
    
  2. 我需要动态创建对象的属性,因此我寻找了一种Type在运行时创建的方法。我最终得到了一个叫做的东西,TypeBuilder但我有点怀疑它是否能解决我的问题。

因此,我想最终的开始是使用,FieldReflector但我不知道如何实现这一点。我正在寻找与上述类似的东西,但这确实有效。

4

1 回答 1

0

你看过FormBuilderJson吗?您可以动态构建 .json 字符串,并在运行时构建表单:

public static IForm<JObject> BuildJsonForm()
{
    string fromFlowJson = GetFormFlowJson();

    return new FormBuilderJson(schema)
         .AddRemainingFields()
         .Build();
}

有关更多信息,请参见此处:https ://docs.microsoft.com/en-us/azure/bot-service/dotnet/bot-builder-dotnet-formflow-json-schema?view=azure-bot-service-3.0

于 2018-06-14T21:13:45.213 回答