JsonForm
在我的MVC核心web应用程序中生成动态表单。我正在使用
System.Text.Json.JsonSerializer.Serialize
在下面的代码中在我的视图模型中生成一个简单的单字段表单。我的目标是最终将这个json存储在数据库中并从那里检索它。
public TestsViewModel GetFormControls1()
{
var myJsonModel = new
{
schema = new
{
client = new
{
type = "object",
title = "Client",
properties = new
{
forename = new
{
type = "string",
title = "Forename",
minLength = 3,
maxLength = 10,
}
}
}
},
form = new List
{
new {
key = "client.forename",
title = "Forename"
}
},
value = new
{
client = new
{
forename = "",
}
}
};
TestsViewModel homeVm = new TestsViewModel();
homeVm.FormControls = System.Text.Json.JsonSerializer.Serialize(myJsonModel);
return homeVm;
}
上面的代码运行良好,并生成以下json模式,然后用于创建表单。
{
"schema": {
"client": {
"type": "object",
"title": "Client",
"properties": {
"forename": {
"type": "string",
"title": "Forename",
"minLength": 3,
"maxLength": 10
}
}
}
},
"form": [
{
"key": "client.forename",
"title": "Forename"
}
],
"value": {
"client": {
"forename": ""
}
}
}
现在我需要为我的json生成一个枚举,以便表单中可以出现一个用于选择性别的下拉列表。但是,我无法通过c代码做到这一点。有人能帮忙吗?我希望我的c代码生成以下json(注意schema和form中的gender有两个条目)。
{
"schema": {
"client": {
"type": "object",
"title": "Client",
"properties": {
"forename": {
"type": "string",
"title": "Forename",
"minLength": 3,
"maxLength": 10
},
"gender": {
"type": "string",
"title": "Gender",
"enum": [
"male",
"female",
"alien"
]
}
}
}
},
"form": [
{
"key": "client.forename",
"title": "Forename"
},
{
"key": "client.gender",
"titleMap": {
"male": "Dude",
"female": "Dudette",
"alien": "I'm from outer space!"
}
}
],
"value": {
"client": {
"forename": ""
}
}
}
我试过使用以下代码,但是
enum
是c中的关键字,所以我得到了错误。
gender = new
{
type = "string",
title = "Gender",
enum = "[male, female, alien]"
}
Enum = "[male, female, alien]"
生产
"Enum": "[male, female, alien]"
而不是
"enum": [ "male", "female", "alien" ]
我有一个性别查找表,我将最终使用产生以上列举不知何故,所以任何关于这方面的想法将是有益的。
更新
@dbc的评论为我的大部分问题提供了解决方案。但是,如果我试图将字符串映射到int,我仍然在努力生成titleMap json。
var gender3 = new
{
type = "string",
title = "Gender",
titleMap = new List { new string("1" + ":" + "Male"), new string("2" + ":" + "Female")}
};
以上代码产生
{
"type": "string",
"title": "Gender",
"titleMap": [
"1:Male",
"2:Female"
]
}
但是,我需要1和Male在{}内使用它们自己的双引号,而不是下面所示的[]。
{
"type": "string",
"title": "Gender",
"titleMap": {
"1": "Male",
"2": "Female"
}
}