【问题标题】:Return json to partial view in core 2将 json 返回到核心 2 中的部分视图
【发布时间】:2018-07-19 15:43:41
【问题描述】:

我想创建一个包含不同视图的视图。我以前从未使用过json。我该如何做到这一点以及如何在视图中格式化 json 数据?

我的第一个函数“Details”是从数据库中检索一个对象并返回视图“Details.cshtml”。在这个视图中,我想生成一个局部视图(“Stats.cshtml”)。现在我想用 Stats 函数中以 json 格式下载的数据生成一个局部视图。

控制器

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”函数时,我得到了视图没有 json 值的“详细信息”和“统计信息”。

【问题讨论】:

  • 我这样做,但在视野中。不知道好不好@{ @using Newtonsoft.Json; @using System.Net; var s = new WebClient().DownloadString("url"); var yourViewModel = JsonConvert.DeserializeObject&lt;App.Models.ViewModel.Person&gt;(s); }@Html.Partial("Stats", yourViewModel)

标签: c# asp.net json asp.net-mvc asp.net-core-2.0


【解决方案1】:

要渲染一个部分,你有很多选择,通过你的代码,

  1. 最简单的方法是:将您的 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.
  1. 由于 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);
    }
    

在您的视图中添加以下代码 - Stats.cshtml:

@model YourViewModel

然后在Details.cshtml中:

@Html.Action("Stats")

注意Html.Action不能调用async动作,小心使用。

  1. 下一个解决方案是使用新功能 ViewComponent,以下是详细信息: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.1

  2. 最后一个将不是您所期望的:使用 AJAX 在页面上加载此部分页面 详细信息已加载到客户端

【讨论】:

  • 我在行中遇到错误:@Html.Partial("Stats")InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为“App.Models.Person”,但此 ViewDataDictionary 实例需要“App.Models.ViewModel.Person”类型的模型项。
  • @Html.Partial("Stats")改成@Html.Action("Stats"),忘记说了。
  • 糟糕,如果您使用的是 ASP.NET 核心,则不能使用已删除的 Html.Acton。给我时间修改我的答案。但是你可以关注这个帖子:stackoverflow.com/questions/26916664/…
  • 非常感谢,您的回答非常广泛且很有帮助。我从 .net 开始冒险,但不知道视图组件存在 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多