I can’t implement a @Foreach on MVC

Asked

Viewed 817 times

2

I’m a beginner in ASP.NET MVC development and I need some help. I’m having trouble creating a Foreach. Follow my code below.

 @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 that’s the one:

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

Man Controller:

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

The error is as follows: Undefined object reference for an object instance

What are we missing? I need help.

2 answers

3


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

So you need to send a list of data:

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

Still, I assume you’re missing the Model in View:

@Model IEnumerable<OTeuProjeto.Models.Fornecedor>
  • Thanks a lot, you’ve already helped me a lot. Apparently you’re almost right. Now I am trying to solve an error that is giving when Debug passes on the line: 'var suppliers = db.Fornecedores.Tolist();' The error that is giving is this one: An Exception of type "System.Data.Entity.ModelConfiguration.Modelvalidationexception" occurred in Entityframework.dll but was not handled in user code Additional information: One or more validation errors Were Detected During model Generation:

  • Quite possibly it is because you do not have a primary key defined in the entity fornecedor. In the model where you have the field codigo, puts public int FornecedorID { get; set; }

  • I put a Dataannotations [Key] for all Primary Keys and no longer gave the error, but did not select from any vendor that is in the bank. I’m looking for the why, if I can help.

  • Yes, it works too. By debugging what gives you the list on fornecedores in the controller?

  • The list returns NULL and says that "Enumeration did not generate results" ?

  • the variable is returning all the list you have in the entity Fornecedor, Are you sure you have data in the comic book?

  • There is data in the database, but returns nothing and also no error. I am not using Where then there are no filters.

  • Yes, the start has to be like this because there are no filters...

  • The error may be in the SELECT that Linq-to-sql is doing. SELECT &#xA; [Extent1].[Codigo] AS [Codigo], &#xA; [Extent1].[NomeFantasia] AS [NomeFantasia], &#xA; [Extent1].[RazaoSocial] AS [RazaoSocial], &#xA; [Extent1].[IE] AS [IE], &#xA; [Extent1].[CNPJ] AS [CNPJ], &#xA; [Extent1].[Ativo] AS [Ativo], &#xA; [Extent1].[Fornecedor_Codigo] AS [Fornecedor_Codigo]&#xA; FROM [dbo].[Fornecedors] AS [Extent1]} Note my last line of code My table calls Vendor and not Vendor. It must be doing the pluralization via Entity Framework

  • I advise you to make a new post with that same question.. I don’t understand what the problem is

Show 5 more comments

1

You weren’t doing anything in her controller, this is the problem. You have to use the controller to first instantiate your class that creates the functions and methods you want to use, and then you have to call these functions to this controller. and after that you have to send her to view.

In your class controller is empty.

Let me give you an example, your controller:

public ActionResult Index()
    {
        caminhodaclasse.nome_da_classe_que_quer_acessar = new caminhodaclasse();
        nome_da_classe_que_quer_acessar.funcao_da_sua_model();
        return View();
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.