[英]Model binding to a custom component - Asp.net Mvc
I found a great json editor that you can download from here and you can see it in action from here . 我发现了一个伟大的JSON编辑器,你可以下载在这里 ,你可以从看到它的行动在这里 。
I want to use it in my asp.net mvc application but I could not figure out how can I bind data to the component. 我想在asp.net mvc应用程序中使用它,但无法弄清楚如何将数据绑定到组件。
Here is my sample code for model and controller: 这是我的模型和控制器的示例代码:
public class TestModel
{
public string Name { get; set; }
public string Json { get; set; }
}
public ActionResult Index()
{
TestModel testModel = new TestModel() { Name = "Test", Json = "{ test: 1 }" };
return View(testModel);
}
And here is the code for my view: 这是我的看法的代码:
@model WebApplication2.Models.TestModel
<br />
<table>
<tr>
<td>
Name
</td>
<td>
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
</td>
</tr>
<tr>
<td>
Json
</td>
<td>
<div id="jsoneditor" style="width:500px;height:500px"></div>
</td>
</tr>
</table>
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var editor = new JSONEditor(container);
//// set json
//document.getElementById('setJSON').onclick = function () {
// var json = {
// 'array': [1, 2, 3],
// 'boolean': true,
// 'null': null,
// 'number': 123,
// 'object': { 'a': 'b', 'c': 'd' },
// 'string': 'Hello World'
// };
// editor.set(json);
//};
//// get json
//document.getElementById('getJSON').onclick = function () {
// var json = editor.get();
// alert(JSON.stringify(json, null, 2));
//};
</script>
Thanks in advance, 提前致谢,
I think you have to use a hidden field
. 我认为您必须使用hidden field
。 Add hidden field to your model save your JSON to that hidden field, and set in $(document).ready()
将隐藏字段添加到模型中,将JSON保存到该隐藏字段,然后在$(document).ready()
Do the followings: 请执行以下操作:
Add a Hidden 添加隐藏
@Html.HiddenFor(model => model.Json, new { id = "hdnJSONField" })
2.Add the following JavaScript 2.添加以下JavaScript
<script>
$(document).ready(function () {
// create the editor
var container = document.getElementById('jsoneditor');
var editor = new JSONEditor(container);
editor.set($('#hdnJSONField').val());
});
You don't even need to use Hidden fields or anything like that. 您甚至不需要使用“隐藏”字段或类似的内容。 This will work as well: 这也将起作用:
Action: 行动:
public ActionResult Index()
{
ViewBag.json = "{ test : 1 }";
return View();
}
View: 视图:
<body>
<div>
<div id="jsoneditor" style="width: 400px; height: 400px;"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var container = document.getElementById("jsoneditor");
var options = {
mode: 'tree'
};
var editor = new JSONEditor(container, options);
var json = @ViewBag.json;
editor.set(json);
});
</script>
</body>
https://github.com/josdejong/jsoneditor/blob/master/docs/usage.md https://github.com/josdejong/jsoneditor/blob/master/docs/usage.md
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.