0

I've had some problems when I try to render a PartialView.

My Controller:

public ActionResult Index()
    {
        var db = new fanganielloEntities();
        List<imovel> imoveis = (from s in db.imovel
                                where s.StatusImovel == 3
                                select s).ToList();

        return PartialView(imoveis);
    }

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

The View:

 @Html.Partial("TesteLista")

The Partial:

@model List Mvc4Web.Models.imovel
    @if (Model != null)
    {
foreach (var item in Model)
{
            @Html.DisplayFor(modelItem => item.DescricaoImovel)
 }
    }

The Error:

Object reference not set to an instance of an object.

Source Error:

Line 5: Line 6: Line 7: @foreach (var item in Model) Line 8: { Line 9:

Thank in advanced!!!

rene
  • 41,474
  • 78
  • 114
  • 152
Rodney
  • 33
  • 10

2 Answers2

3

You should pass Model to the partial View

In your View

 @model List<Mvc4Web.Models.imovel>
@Html.Partial("TesteLista",Model)
Shivkumar
  • 1,903
  • 5
  • 21
  • 32
  • Thanks for your help, but I still getting the same result: Object reference not set to an instance of an object. – Rodney Oct 11 '12 at 12:42
  • For the line `@Html.DisplayFor(modelItem => item.DescricaoImovel)` I believe you'll need `@Html.DisplayFor(item => item.DescricaoImovel)` as this doesn't appear to be a valid lambda expression - see http://stackoverflow.com/questions/10097995/i-want-to-understand-the-lambda-expression-in-html-displayformodelitem-mymo and http://msdn.microsoft.com/en-us/library/bb397687.aspx – Aaron Newton Oct 14 '12 at 07:05
0

Html.Partial will not fire your controller action. If you want to fire the Index action when TesteLista is rendered, use

@Html.Action("TesteLista") 

instead.

Forty-Two
  • 7,535
  • 2
  • 37
  • 54
  • Thats what I got: A public action method 'TesteLista' was not found on controller 'Mvc4Web.Controllers.TesteController'. – Rodney Oct 11 '12 at 12:44
  • @Rodney 'TesteLista' is not action it partial view so you only have Partial View. and insead of checkinh if(Model !=null) check if(Model.Count >0) and check whether you are passing Model in View or not and same model forwarding to partial view. – Shivkumar Oct 11 '12 at 13:01
  • @Rodney, rename Index() to TesteLista(). – Forty-Two Oct 11 '12 at 13:15