Error in view when using DisplayFor and foreach

2

I made this html within my cshtml. I was doing a foreach and gave error in foreach and also did not recognize modelItem. In the Models folder are my edmx, so T_PDV is a BD entity mapped to 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 in foreach and DisplayFor respectively

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.
    
asked by anonymous 14.05.2014 / 16:14

1 answer

2

SuporteTecnico.Models.T_PDV is your class.

To interact with 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 your Action , on Controller , you would return a list:

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