I can not implement an @Foreach in MVC

2

I am a beginner in ASP.NET MVC development and need some help. I can not create a Foreach . Below is my code.

 @foreach (var item in Model.Fornecedores)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => modelItem.Codigo)
        </td>
        <td>
            @Html.DisplayFor(modelItem => modelItem.NomeFantasia)
        </td>
        <td>
            @Html.DisplayFor(modelItem => modelItem.RazaoSocial)
        </td>
        <td>
            @Html.DisplayFor(modelItem => modelItem.CNPJ)
        </td>           
    </tr>
}

My model is this:

 public partial class Fornecedor
{
    public Fornecedor()
    {
        this.Entrada = new HashSet<Entrada>();
        this.Produto = new HashSet<Produto>();
    }

    public int Codigo { get; set; }

    [Required(ErrorMessage="Nome fantasia é obrigatório", AllowEmptyStrings=false)]
    public string NomeFantasia { get; set; }

    [Required(ErrorMessage = "Razão Social é obrigatório", AllowEmptyStrings = false)]
    public string RazaoSocial { get; set; }

    [Required(ErrorMessage = "Inscrição Estadual é obrigatório", AllowEmptyStrings = false)]
    public string IE { get; set; }

    [Required(ErrorMessage = "CNPJ é obrigatório", AllowEmptyStrings = false)]
    public string CNPJ { get; set; }

    public Nullable<bool> Ativo { get; set; }


    public virtual ICollection<Entrada> Entrada { get; set; }
    public virtual ICollection<Produto> Produto { get; set; }

    public virtual ICollection<Fornecedor> Fornecedores { get; set; }
}

My Controller :

public ActionResult Index()
    {
        return View();
    }

The error is as follows: Object reference not set to an instance of an object

What's missing? I need some help.

    
asked by anonymous 01.09.2015 / 15:12

1 answer

4

The error is occurring because you have to send the data list to the view, of the type of data you receive in Model on the view side.

So you have to submit a list of data:

public ActionResult Index()
{
    var fornecedores = db.Fornecedor.ToList();
    return View(fornecedores);
}

Still, I assume you're missing instantiating Model in View:

@Model IEnumerable<OTeuProjeto.Models.Fornecedor>
    
01.09.2015 / 15:15