c# - MVC - 如何显示列表?
问题描述
我是 MVC 新手,我正在尝试在 MVC 视图类中填充项目列表,但在启动期间,.cshtml 文件中的模型对象为空。
@foreach (var element in Model)
谢谢你的帮助。
我的代码:
public class HomeController : Controller
{
List<ModelMath> mathList = new List<ModelMath>();
[HttpPost]
public ActionResult Submit(FormCollection fc)
{
mathList = new List<ModelMath>();
int num = Convert.ToInt32(fc["Num"]);
while(num > 1)
{
ModelMath modelMath = new ModelMath();
modelMath.Number = num;
mathList.Add(modelMath);
num--;
}
return View(mathList);
}
}
型号类:
public class ModelMath
{
public int Number { get; set; }
}
索引.cshtml
@{
ViewBag.Title = "Home Page";
}
<h3><b>HTTPPost Method</b></h3>
@using (Html.BeginForm("Submit", "Index", FormMethod.Post))
{
<table>
<tr>
<td>Enter a Number: </td>
<td>@Html.TextBox("Num")</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
}
<h4 style="color:purple">
<div class="panel-body">
<div class="col-md-12" style="margin-top: 15px;">
<table class="table table-bordered table-responsive table-hover">
<tr>
<th>Input Numbers </th>
</tr>
@foreach (var element in Model)
{
<td>@d.Number</td>
}
</table>
</div>
</div>
</h4>
你能告诉我我的代码有什么问题吗?再次感谢你的帮助。
解决方案
在您的 Index 函数中,您需要填充模型并传递给视图。就像是
Public ActionResult Index()
{
var myList = new List<example>();
return view(myList)
}
在您看来:
@model List<example>
这就是填充索引视图模型的内容。如果您向我们展示返回索引视图的控制器函数,将会有所帮助。
推荐阅读
- swift - 为什么类的常量实例可以在属性值中更改?
- java - 在socket通信中设置FIN & RST
- python - 使用 numpy. binary_repr 上的数字或替代数组 - Python
- python - 如何将Django源安装转换为包安装
- mysql - mysql中使用count()和join时返回错误值
- graph - 如何将单元格中的字符串用作图形数据范围?
- python - 错误 - OSError:读取文件“http://website”时出错,无法加载外部实体“http://website/alpha.html”
- google-apps-script - 扫描数据后自动推进单元格
- android-studio - 更新列表视图中元素的数据
- python - matplotlib 网站的原始代码不起作用