Reputation: 39
I'm trying to pass a list of values from the controller to the view, but apparently I got this issue where the list cannot be passed. I already tried passing one value and it has no problem. But when I try to pass list, it show the following error -
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[vidly.Models.pelanggan]', but this dictionary requires a model item of type 'vidly.models.pelanggan'.
I have this model -
public class pelanggan
{
public string Nama { get; set; }
}
The controller code -
// GET: Pelanggan
public ActionResult Index()
{
var name = new List<pelanggan> {
new pelanggan {Nama = "Paidi" },
new pelanggan {Nama = "Budi" }
};
return View(name);
}
This is my view file
@model vidly.Models.pelanggan
@{
ViewBag.Title = "index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Customer</h2>
@foreach(var Nama in Model.pelanggan)
{
<li>@Nama.Nama</li>
}
I already tried to create a ViewModel
but it also showing same error. Can you point where the error is?
Upvotes: 0
Views: 472
Reputation: 8325
You are returning a List<T>
from the controller. So, the model declared in your view should be able to receive a list and iterate over it.
Replace the model declaration in the view file with following -
@using vidly.Models;
@model IEnumerable<pelanggan>
Then you can iterate/loop over the model like -
@foreach(var p in Model) // p represents a "pelanggan" object in the list
{
<li>@p.Nama</li>
}
Upvotes: 2
Reputation: 26460
The problem is the missmatch of types between what you return return View(name);
and what te view expects @model vidly.Models.pelanggan
You could change to @model List<vidly.Models.pelanggan>
but instead I'd say:
public class pelanggan
{
public List<string> Namas { get; set; }
}
Then
public ActionResult Index()
{
var model = new pelanggan {
name = new List<string> {
"Paidi",
"Budi"
}
};
return View(model);
}
And finally in your view
@foreach(var Nama in Model.Namas)
{
<li>@Nama</li>
}
Upvotes: 1