应该创建具有来自类似 json 的符号字符串的附加属性的对象。 方法将从 Razor View 调用以将 colmodel 传递给 jqgrid 像 json 对象一样
@Html.Raw( Json.Encode( Model.GetColModel()))
方法应该有这样的签名
object GetColModel(string colName, int colWidth, string additonalProperties)
例如,
GetColModel("customer", 17, "address=\"Toronto\", index=1555" )
应该返回对象
new { colName="customer", colwidth=17, address="Toronto", index=1555 }
可能存在嵌套属性,例如 JSON 中的 eq。
GetColModel("customer", 17, "formatoptions= new { formatter=\"number\", editable=true } " )
应该返回对象
new { colName="customer", colwidth=17, formatoptions=new {
formatter="number",
editable=true
}
}
我试过方法
public object GetColModel(string colName, int colWidth, string additonalProperties)
{
return new
{
name = colName,
width = colWidth,
&addtitionalProperties
};
}
但这失败了,因为 C# 不支持宏
如何创建这样的方法或其他方式将属性从数据库添加到 Razor View 中的 json 字符串?
它是从 ASP.NET/Mono C# MVC 4 View 模型调用的。 使用了 Razor View 和 RazorEngine。
最佳答案
没有任何内置的东西可以做到这一点,但是你使用字符串解析你的字符串(string.Split 会让你在 ',' 上分割,但是如果你的文本中可能有那些,你将不得不构建一个真正的解析器,或者将您的字符串格式切换为 CSV 之类的格式,在那里您可以找到很多解析器。您可以找到一个简单语法的属性解析器。或者您将其他属性字符串推送为 json 并使用 Json.net 进行解析。
一旦将字符串解析为键/值结构,就可以使用 ExpandoObject 填充最终对象并返回它。
https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx
关于c# - 从字符串中的属性创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35106538/