【发布时间】:2023-02-06 10:42:25
【问题描述】:
首先,对不起我的英语,我是法国人。
我不太擅长开发,因为我没有学过它,但我正在尝试创建一个网站,在其中显示来自 SIEMENS 模块的数据。
但是出现了那个错误:NullReferenceException: Object reference not set to an instance of an object. AspNetCoreGeneratedDocument.Views_Machine_Index.ExecuteAsync() in Index.cshtml @foreach (var item in ModelI
所以我在 ASP.NET Core MVC 上创建了 3 个文件(开发人员建议我使用这个框架)。 这是我使用 json 文件自动创建的 JsonObject.cs:
using System.Text.Json;
namespace Auth.Models
{
public class JsonObject
{
public int mode_auto { get; set; }
public int mode_arret_urgence { get; set; }
public int mode_secours { get; set; }
public int BP_avancer_bobine { get; set; }
public int BP_avancer_debut { get; set; }
public int BP_avancer { get; set; }
public int BP_reculer { get; set; }
public int Guillotine { get; set; }
public int Gouttiere_detecte { get; set; }
public int taille_debitee { get; set; }
public int long_demande { get; set; }
public int long_sortie { get; set; }
public int nbs_angles { get; set; }
}
}
然后,这是我的控制器(称为 SiemensController.cs):
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace Auth.Controllers
{
public class SiemensController : Controller
{
public ActionResult Index()
{
List<Auth.Models.JsonObject> jsonObjects = new List<Auth.Models.JsonObject>();
string baseurl = "http://31.43.187.129/awp/Profileuse/test.json";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseurl);
HttpResponseMessage Res = client.GetAsync(baseurl).Result;
if (Res.IsSuccessStatusCode)
{
var response = Res.Content.ReadAsStringAsync().Result;
jsonObjects = JsonConvert.DeserializeObject<List<Auth.Models.JsonObject>>(response);
}
return View(jsonObjects);
}
}
}
}
还有我的 HTML 文件:
@Model Auth.Models.JsonObject
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<th>mode_auto</th>
<th>mode_arret_urgence</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td><%: item.mode_auto %></td>
<td><%: item.arret_urgence %></td>
</tr>
}
</table>
我是新手,我不太了解 Controllers 如何使用 Views 等。 如果你能帮助我并向我解释它是如何工作的?
谢谢 :)
此致,
玛丽
【问题讨论】:
-
上一些课程或看一些复数视觉的视频而不是直接跳过
-
似乎您从未定义过模型(您正在尝试对其进行迭代)-这也是您获得 NullRefereceException 的原因
-
请在
jsonObjects = JsonConvert.DeserializeObject<List<Auth.Models.JsonObject>>(response);设置断点以查看 jsonObjects 的结果。
标签: c# asp.net-core-mvc