我想创建一个包含不同 View 的 View 。我以前从未使用过 json。我该怎么做以及如何格式化 View 中的 json 数据?
我的第一个函数“Details”是从数据库中检索一个对象并返回 View “Details.cshtml”。在此 View 中,我想生成一个局部 View (“Stats.cshtml”)。现在我想生成一个局部 View ,其中包含在 Stats 函数中以 json 格式下载的数据。
Controller
public IActionResult Details(int? id = 1)
{
var person = _context.Persons.Find(id);
return View(champion);
}
public IActionResult Stats()
{
var json = new WebClient().DownloadString("url");
return Json(s);
}
查看 - Details.cshtml
@model Person
<div class=row">
<div class="col-sm-5"> @Model.Name </div>
<div class="col-sm-5"> @Html.Partial("Stats") </div>
</div>
查看 - Stats.cshtml
<h2>Stats</h2>
<div> here I want to put in a json field </div>
当我从地址 localhost/Home/Stats 运行“Stats”函数时,我得到了 json 格式的结果,但是当我运行“Details”函数时,我得到了 View 没有 json 值的“详细信息”和“统计信息”。
最佳答案
要渲染局部,你有很多选择,通过你的代码,
最简单的方法是:将您的 Stats 代码移动到 Details 操作
public ActionResult Details() { ...//prepare your person viewModel var result = new WebClient().DownloadString("url"); var stats = JsonConvert.DeserializeObject<YourViewModel>(result); //you have 2 options to return data yourPersonModel.Stats=stats ; //<== you have to change PersonViewModel //or ViewBag.Stats=stats; return View(yourPersonModel); }
然后在 Details.cshtml 中:
@Html.Partial("Stats", ViewBag.Stats or Model.Stats)//by your choice before.
由于 Html.Action 被移除,但 ViewComponent 包含在 Core 中,您现在不能直接调用它,但此链接将告诉您如何恢复它:@Html.Action in Asp.Net Core
public ActionResult Stats() { var result = new WebClient().DownloadString("url"); var yourViewModel = JsonConvert.DeserializeObject<YourViewModel>(result); return PartialView(yourViewModel); }
在您的 View 中添加以下代码 - Stats.cshtml:
@model YourViewModel
然后在 Details.cshtml 中:
@Html.Action("Stats")
请注意,Html.Action
不能调用async
操作,请谨慎使用。
下一个解决方案是使用新功能 ViewComponent,详情如下: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.1
最后一个不会是你所期望的:使用 AJAX 加载此部分页面在页面详细信息加载到客户端
关于c# - 将 json 返回到核心 2 中的部分 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51426881/