嗨,我过去一个小时一直在尝试将我的 c# 后端连接到前端以输出列表。
我一直想知道将数据从后端传递到前端的最佳方式是什么。
在我的场景中,我只想从 mvc 中输出一个简单的列表,但是如何将我的列表发送到前端,这样我就可以做一些简单的事情,例如使用 foreach 之类的输出表中的所有数据:
foreach (var value in customerList) {
<p>value.Name</p>
}
我查看了此链接中建议的解决方案:How to pass List from Controller to View in MVC 3.作者:archil
但我不知道该放在哪里
protected 内部 ViewResult View (
对象模型
)
那么如何输出我的列表呢?
我知道该列表包含内容,因为我已经放置了一个断点并逐步完成了它。
这就是我的代码的样子:
public List<Customer> customerList = new List<Customer>();
public ActionResult Index()
{
var client = new CustomerAzureAPIApp();
var response = client.Customer.Get();
var customers = response;
foreach (var customer in customers)
{
customerList.Add(customer);
}
return View();
}
我知道我可以使用 ViewBag,但我不想为列表中的每个项目创建一个新的 ViewBag,我宁愿只发送整个列表。有什么建议?
最佳答案
好吧,我不知道最佳解决方案,但不要对您提供的链接中 archil 建议的代码感到困惑。
您只需将您的 customerList 与
return View(customerList);
作为参数,因为该行代码通过使用将 View 呈现给响应的模型自动创建 ViewResult 对象。
所以在你的前端,你最终可能会为你的 table 做这样的事情:
<table
<tr>
<th>ID</th>
<th>Name</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
</tr>
}
</table>
请记住在您的项目之前有“@”,因为我们正在处理 Razor View 引擎。
关于c# - 如何在 ASP.NET 中将列表从后端传递到前端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36338567/