john smith
john smith

Reputation: 31

asp.net mvc repeater using foreach

I'm building a website in ASP.NET MVC, and I need to save the value of a form in table so I used foreach as repeater but I get an error

NullReferenceException: La référence d'objet n'est pas définie à une instance d'un objet. AspNetCore.Views_Home_Resultat.ExecuteAsync() in Resultat.cshtml + @foreach (var item in Model.Itemlst)

Model:

public class Customers
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Customers> Itemlst { get; set; }
}

Controller:

public ActionResult List()
{
     Customers itemobj = new Customers();

     return View(itemobj);
}   

View:

@foreach(var item in Model.Itemlst)
{
     <tr>
          <td>Items ID:</td>
          <td>@item.ID</td>
          <td>Items Name:</td>
          <td>@item.Name</td>
     </tr>
}
</table>
<form asp-controller="Home" asp-action="resultat" method="post" runat="server">
    <div class="form-style-5">

        <table>
            <tr>
                <td>
                    ID :
                </td>
                <td>
                    <input type="number" name="Id" required />
                </td>
            </tr>
            <tr>
                <td>
                    Name :
                </td>
                <td>
                    <input type="number" name="Name" required />
                </td>
            </tr>



            <tr>
                <td>
                    <input type="submit" name="resultat" value="show solution" />
                </td>
            </tr>


        </table>
    </div>
</form>

Upvotes: 0

Views: 434

Answers (1)

Hadi Samadzad
Hadi Samadzad

Reputation: 1540

You should initialize the Itemlst as shown below:

public class Customers
{
    public Customers()
    {
        Itemlst = new List<Customers>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public List<Customers> Itemlst { get; set; }
}

Upvotes: 1

Related Questions