首页 > 解决方案 > 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>

你能告诉我我的代码有什么问题吗?再次感谢你的帮助。

标签: c#asp.net-mvcrazor

解决方案


在您的 Index 函数中,您需要填充模型并传递给视图。就像是

Public ActionResult Index()
{
    var myList = new List<example>();
    return view(myList)
}

在您看来:

@model List<example>

这就是填充索引视图模型的内容。如果您向我们展示返回索引视图的控制器函数,将会有所帮助。


推荐阅读