Reputation: 21
I have this model:
public class RamalModel
{
public int ID { get; set; }
public string Nome { get; set; }
public int Numero { get; set; }
}
And I create a partial view:
@model RamalAguia.Models.RamalModel
<div>
<h4>@Model.Nome</h4>
<span>@Model.Numero</span>
<hr />
</div>
In my controller I'm using it:
public class HomeController : Controller
{
RamaDb _db = new RamaDb();
public ActionResult Index()
{
var model = _db.Ramais.ToList();
return View(model.ToList());
}
}
But when I try to put:
@Html.RenderPartial("_Ramal", Model.Nome , new ViewDataDictionary());
It doesn't work and shows this error:
Error 1 'System.Collections.Generic.List' does not contain a definition for 'Nome' and no extension method 'Nome' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?) c:\dev\Teste\RamalAguia\RamalAguia\Views\Home\Index.cshtml 9 37 RamalAguia
Someone can help me? Thanks
Upvotes: 1
Views: 1142
Reputation: 21
SOLVED
In my partial view:
@model List<RamalAguia.Models.RamalModel>
@{
foreach(var item in Model) {
<h4>@item.Nome</h4>
<span>@item.Numero</span>
<hr />
}
}
And in my Index:
@model List<RamalAguia.Models.RamalModel>
@Html.Partial("_Ramal", Model);
Thanks for help.
Upvotes: 1
Reputation: 5764
Your model is List<RamaModel>
and you in
@Html.RenderPartial("_Ramal", Model.Nome , new ViewDataDictionary());
trying to get from variable type RamaModel
not from list.
For render first elemet you can use:
@Html.RenderPartial("_Ramal", Model[0].Nome , new ViewDataDictionary());
Or for show all ramas in list:
@foreach (var item in Model)
{
@Html.RenderPartial("_Ramal", item.Nome , new ViewDataDictionary());
}
EDIT
In View
Change
@model RamalAguia.Models.RamalModel
to
@model List<RamalAguia.Models.RamalModel>
And in controller
return View(model.ToList());
.ToList()
is unnecessary.
Upvotes: 2
Reputation: 2190
I'm not sure what you want to accomplish but I'm assuming you want to display a list of RamalModel
on a page. In your controller:
public ActionResult Index()
{
var model = _db.Ramais.ToList();
return View(model);
}
And when rendering your partial:
@model List<RamalAguia.Models.RamalModel>
...
@Html.RenderPartial("_Ramal", Model, new ViewDataDictionary());
and inside your partial, to loop through the list:
@model List<RamalAguia.Models.RamalModel>
foreach(var item in Model) {
<h4>@item.Nome</h4>
<span>@item.Numero</span>
<hr />
}
Another approach:
You can loop through the list and render a partial view for each one, depends on what you want to achieve:
@model List<RamalAguia.Models.RamalModel>
foreach(var item in Model) {
@Html.RenderPartial("_Ramal", item, new ViewDataDictionary());
}
Upvotes: 0