sti*_*boe 5 c# linq json json.net asp.net-mvc-4
我正在使用Json.net进行序列化,然后创建一个如下所示的JObject:
"RegistrationList": [
{
"CaseNumber": "120654-1330",
"Priority": 5,
"PersonId": 7,
"Person": {
"FirstName": "",
"LastName": "",
},
"UserId": 7,
"User": {
"Id": 7,
"CreatedTime": "2013-07-05T13:09:57.87",
"Comment": "",
},
Run Code Online (Sandbox Code Playgroud)
我如何查询到一个新的对象或列表,这很容易放入一些html表/视图.我只想显示CaseNumber,FirstName和Comment.
我只想显示CaseNumber,FirstName和Comment.
与ASP.NET MVC一样,您可以从编写符合您要求的视图模型开始:
public class MyViewModel
{
public string CaseNumber { get; set; }
public string FirstName { get; set; }
public string Comment { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后在您的控制器操作中,您从已有的JObject实例构建视图模型:
public ActionResult Index()
{
JObject json = ... the JSON shown in your question (after fixing the errors because what is shown in your question is invalid JSON)
IEnumerable<MyViewModel> model =
from item in (JArray)json["RegistrationList"]
select new MyViewModel
{
CaseNumber = item["CaseNumber"].Value<string>(),
FirstName = item["Person"]["FirstName"].Value<string>(),
Comment = item["User"]["Comment"].Value<string>(),
};
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
最后在强类型视图中显示所需信息:
@model IEnumerable<MyViewModel>
<table>
<thead>
<tr>
<th>Case number</th>
<th>First name</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.CaseNumber</td>
<td>@item.FirstName</td>
<td>@item.Comment</td>
</tr>
}
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9730 次 |
| 最近记录: |