ViewData 返回 null 而不是列表元组



Hellow,

我正在将 ASP.NET CORE与Razor Pages一起使用,并且我正在尝试完成使ViewData返回列表元组的最后一步。 我让事情按照我想要的方式工作,我让 2 个不同的 ViewData 返回 2 个列表,但它的顺序不是我想要的,所以我将它们都放在一个元组中,以一个接一个地返回 2 个列表,主题、文本、主题、文本等。

在我的服务类中创建数据并将其添加到元组:

public Tuple<List<string>, List<JToken>> get_data_om_mig_info_data()
{
StreamReader reader = File.OpenText(json_file_name);
JToken data = JToken.Parse(reader.ReadToEnd());
JObject om_mig_info = data["om_mig_info"].Value<JObject>();
List<string> subjects = om_mig_info.Properties().Select(property => property.Name).ToList();
List<JToken> text = om_mig_info.Properties().Select(property => property.Value).ToList();
Tuple<List<string>, List<JToken>> om_mig_data = new Tuple<List<string>, List<JToken>>(subjects, text);
return om_mig_data;
}

索引.cs: 在这里,Tuuple 按预期获得了所有项目。项目 1 计数 = 3,项目 2 计数 = 3。 但视图数据仍然为空。

public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public string Index_title { get; private set; }
public Data_Info_Service Om_mig_service_text { get; set; }
public Tuple<List<string>, List<JToken>> Tuuple { get; set; }
public object aaa;
public IndexModel(ILogger<IndexModel> logger, Data_Info_Service Om_mig_service_text)
{
_logger = logger;
this.Om_mig_service_text = Om_mig_service_text;
}
public void OnGet()
{
Tuuple = Om_mig_service_text.get_data_om_mig_info_data(); // Tuple works
ViewData["data_text"] = Tuuple;
aaa = ViewData["data_text"]; // aaa seems to work as well, has all items
Index_title = "Om mig";
}
}

视图:

<div class="data_position">
@foreach (var data in ViewData["data_text"] as IEnumerable<Tuple<List<string>, List<Newtonsoft.Json.Linq.JToken>>>) // Exception here
{
<h5>@data</h5>
}
</div>

例外:

System.NullReferenceException: 'Object reference not set to an instance of an object.'
(... as System.Collections.Generic.IEnumerable<System.Tuple<System.Collections.Generic.List<string>, 
System.Collections.Generic.List<Newtonsoft.Json.Linq.JToken>>>) returned null.

任何帮助将不胜感激,谢谢。

我认为这应该有效:

public void OnGet()
{
Var datas = ViewData["data_text"] as Om_mig_service_text.get_data_om_mig_info_data();}


视图中的演员表无效。 不能将包含 2 个列表的元组转换为单个列表。

<div class="data_position">
@{
var data = ViewBag.data_text;
var list1 = data.Item1 as List<string>;
var list2 = data.Item2 as List<string>;
}
@foreach (var item in list1)
{
<h5>@item</h5>
}
</div>

最新更新