实体字符串未在C#中解码

时间:2018-07-30 20:45:49

标签: c# json asp.net-mvc decode

我在SQL Server数据库的文本列中输入了以下JSon:

{
 "tag" : {
  "string" : "<input type=\"text\" [attributes] />",
  "attributes" : {
   "name" : {
    "required" : true,
    "label" : "Field name",
    "description" : "Use only letters and minus sign",
    "expert" : false
   },
   "id" : {
    "required" : false,
    "label" : "Field identifier",
    "description" : "Use only letters and minus sign",
    "expert" : true
   },
   "class" : {
    "required" : false,
    "default" : "form-control",
    "label" : "Field styles",
    "description" : "These must exist in the stylesheet, leave blank if you don't know about them",
    "expert" : true
   },
   "required" : {
    "required" : false,
    "allowed" : [
     "required",
     ""
    ],
    "label" : "Is the field required?",
    "description" : "If the user must enter a value in this field, use the word required",
    "expert" : true
   },
   "pattern" : {
    "required" : false,
    "label" : "Input pattern that must be followed",
    "description" : "This is a regular expression that will validate the field's value",
    "expert" : true
   },
   "autocomplete" : {
    "required" : false,
    "default" : "off",
    "allowed" : [
     "on",
     "off",
     ""
    ],
    "label" : "Allow autocomplete?",
    "description" : "If you wish the browser's built in autocomplete to remember the answer, set this on",
    "expert" : true
   },
   "placeholder" : {
    "required" : false,
    "label" : "Hint for the user",
    "description" : "Write an example value that can be entered in this field",
    "expert" : false
   }
  }
 }
}

好,因此基本上,此JSon包含对输入字段的描述及其所有可能的属性。 标签键中的字符串键是字段的基本结构。在另一个表中,我基于该结构创建了一个字段,并且在JSon中具有以下信息:

{
 "tag" : {
  "name" : "username",
  "id" : "username",
  "class" : "form-control",
  "placeholder" : "Enter your name"
 }
}

使用C#,我想将该字段呈现为表单:

public string RenderField()
    {
        var data = JObject.Parse(this.Data); //Data is the field that contains the definition of the field
        var structure = JObject.Parse(this.FieldTypes.Datos); // FieldTypes defines the structure of each possible field type
        string tagHtml = structure["tag"]["string"].ToString(); // This is the basic form of a form field
        foreach(JProperty key in data["tag"])
        {
            tagHtml = tagHtml.Replace("[attributes]", key.Name + "=\"" + key.Value + "\" [attributes]");
        }
        return WebUtility.HtmlDecode(tagHtml).Replace("[attributes]", "");
    }

基本上一切都按预期工作,但是由于某些原因,该字段未显示,但其htmlentities如下所示:

&lt;input type=&quot;text&quot; name=&quot;username&quot; id=&quot;username&quot; class=&quot;form-control&quot; placeholder=&quot;Enter your name&quot;  /&gt;

我不知道为什么它不解码字符串。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您正在尝试显示html,但问题不在方法中,而在于您没有在mvc中正确打印它。是否像建议的here一样:

@Html.Raw(RenderField())