Error in view when using Displayfor and foreach

Asked

Viewed 297 times

2

I made this html inside my cshtml. I went to do a foreach and it was an error in foreach and also did not recognize modelItem. In the Models folder are my edmx, so T_PDV is a BD entity mapped in this edmx.

@model SuporteTecnico.Models.T_PDV
@{
     ViewBag.Title = "Formulário";
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Pesquisa</title>
</head>
<body>
    <table>
     <tr>
          <th>@Html.DisplayNameFor(model => model.RazaoSocial)</th>
          <th>@Html.DisplayNameFor(model => model.CNPJ)</th>
     </tr>
    @foreach (var item in Model) {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.RazaoSocial)</td>
            <td>@Html.DisplayFor(modelItem => item.CNPJ)</td>
        </tr>
    }
    </table>
</body>
</html>

Below the errors respectively in foreach and Displayfor

foreach statement cannot operate on variables of type 'V99SuporteTecnico.Models.T_PDV' because 'V99SuporteTecnico.Models.T_PDV' does not contain a public definition for 'GetEnumerator'    


The type arguments for method 'System.Web.Mvc.Html.DisplayExtensions.DisplayFor<TModel,TValue>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TValue>>)' 
cannot be inferred from the usage. Try specifying the type arguments explicitly.

1 answer

2


SuporteTecnico.Models.T_PDV is your class.

To interact with the foreach you need to use a list, an array...

Your code should be, for example, like this:

@model List<SuporteTecnico.Models.T_PDV>
@{
     ViewBag.Title = "Formulário";
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Pesquisa</title>
</head>
<body>
    <table>
    <tr>
          <th>@Html.DisplayNameFor(model => model[0].RazaoSocial)</th>
          <th>@Html.DisplayNameFor(model => model[0].CNPJ)</th>
    </tr>
    @foreach (var item in Model){
        <tr>
            <td>@Html.DisplayFor(modelItem => item.RazaoSocial)</td>
            <td>@Html.DisplayFor(modelItem => item.CNPJ)</td>
        </tr>
    }
    </table>
</body>
</html>

So in his Action, in the Controller, you would return a list:

public ActionResult Listar()
{
    var lista = new List<SuporteTecnico.Models.T_PDV>();
    ... // popular a lista
    return view(lista);
}
  • 3

    I did with Ienumerator<... Models.T_PDV> and it worked.

Browser other questions tagged

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