Search code examples
c#asp.net-mvcrazor

MVC - How to display a list?


I am new to MVC and I am trying populate a list of item in the MVC view class, but the model object is null in the .cshtml file during the startup.

    @foreach (var element in Model)

Thanks for your help.

My Code:

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);

    }

}

Model class:

public class ModelMath
{
    public int Number { get; set; }
}

Index.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>

Could you please let me know what's wrong with my code? Thanks again for your help.


Solution

  • In your Index function, you need to populate the model and pass to the view. Something like

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

    and in your view:

    @model List<example>
    

    That is what populates your index view model. It would help if you show us the controller function returning your index view.