1

我想用手动添加和动态添加的字段填充表单。

public class ModelClass
{
    [Prompt("URL?")]
            public string URL { get; set; }
            [Prompt("Name?")]
            public string Title { get; set; }
}

表单生成器:

 public IForm<ModelClass> BuildApplyform()
        {
            var builder = new FormBuilder<ModelClass>(); 
            // Parse string to json for usage in the foreach
            dynamic json = JObject.Parse(jsonString);

            builder.Message("Form builder");
            builder.Field(nameof(ModelClass.Title), active: (state) => false);
            builder.Field(nameof(ModelClass.URL), active: (state) => false);
            foreach(string param in json.Parameters)
            {
                builder.Field(param);
            }
            return builder.Build();
        }

JSONstring 非常动态,每次都可能不同。但是,字符串始终包含“d”和“parameter”子节点。该字符串可能如下所示:

"{
  \n\t\"d\":  {
    \n\t\t\"parameters\":  [
      {
        \n\t\t\t\"id\":  \"url\",
        \n\t\t\t\"name\":  \"Site URL\",
        \n\t\t\t\"required\":  \"text\"
      },
       {
        \n\t\t\t\"id\":  \"title\",
        \n\t\t\t\"URL\":  \"Title\",
        \n\t\t\t\"required\":  true,
        \n\t\t\t\"example\":  \"www.stackoverflow.com\"\n\t\t
      }
    ]\n\t
  }\n
}"

如何确保无论 JSON 是什么样子,参数都作为字段输入动态添加到表单构建器中?提前致谢。

4

1 回答 1

1

不可能的

好吧,经过更多研究后,我发现我想要达到的目标几乎是不可能的。使用 Bot Framework 无法同时动态添加字段和添加静态字段。因此,在这种情况下,formbuilder 是不现实的。正如 Eric Dahlvang 所提到的:当您仅通过带有表单构建器的 JSON 模式使用 JSON 时,这是一种可能性。

我是如何解决这个问题的:

在我使用 Form Builder 的搜索过程中,我偶然发现了一个循环通过提示对话框的解决方案。可以读取 JSON 并将其转换为 C# 对象,以便您可以迭代它们,那么为什么不使用它呢?

全局定义字符串列表,或者像我使用的“参数对象”:

public class Parameter
{
    public string Id { get; set; }
    public string Title { get; set; }
    public bool Required { get; set; }
    public string Example { get; set; }
}

然后,您必须获取 JSON 参数并将它们转换为 C# 对象(参数)。稍后我使用全局列表来访问参数。然后我提示第一个问题(参数),因此循环开始。作业包含解析的 JSON。

    public void SomeFunction(IDialogContext context)
{
        if (job["d"]["parameters"] != null)
                    {
                        var t = job["d"]["parameters"];
                        parameters = GetParametersFromJSON(t); // parameters is a globally defined list of <Parameter>
                    }
                    currentParameter = parameters[0];
                    PromptDialog.Text(context, ParamPrompt, "Please fill in: " + currentParameter.Title+ $", for example: {currentParameter.sampleValue}");
}



private async Task ParamPrompt(IDialogContext context, IAwaitable<string> 
result)
{
    var answer = await result;

        index++;
        if (index < parameters.Count)
        {
            currentParameter = parameters[index];
            PromptDialog.Text(context, ParamPrompt, "Please fill in: " + currentParameter.Title + $", for example: {currentParameter.example}");
        }
       else 
       {
           // handle logic, the loop is done.
       }
    }
于 2018-04-19T09:20:38.377 回答