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?
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>
}
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>
}
Related
I have a project to make an online shop between users (post a product, buy, etc.) using a database. In this project I have a view called "ShoppingCart":
#model IEnumerable<MyFirstProject.Models.Product>
#{
ViewBag.Title = "ShoppingCart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Your Shopping Cart</h2>
#if (Model == null)
{
<div style="float:left">Your cart is empty.</div>
<div>
Total payment: 0
</div>
}
else
{
decimal tPrice = 0;
<div>
<table style="float:left">
#foreach (var product in Model)
{
tPrice = tPrice + product.Price;
{ Html.RenderPartial("ProductLine", product);}
}
</table>
</div>
<div>
Total payment: #tPrice
</div>
}
It receives a list of products which the user decided to buy and displays them (not the important part). I need to add a button which will send the list to an action result in the "ShoppingController":
[HttpPost]
public ActionResult ShoppingCart(List<Product> bought)
{
if (ModelState.IsValid)
{
foreach (var listP in bought.ToList())
{
foreach (var databaseP in db.Products.ToList())
{
if (listP.ProductID == databaseP.ProductID)
{
databaseP.State = 1;
db.SaveChanges();
break;
}
}
}
return RedirectToAction("Index");
}
else
{
return View(bought);
}
}
"State" indicates if the product was bought or not (0=not bought, 1=bought), db is the database
If you wan't to post any data from a view to an action method, you should keep that data in form elements and keep that in a form. Since you want to post a collection of items, You may use Editor Templates.
Let's start by creating a view model.
public class ShoppingCartViewModel
{
public decimal TotalPrice { set; get; }
public List<Product> CartItems { set; get; }
}
public class Product
{
public int Id { set; get; }
public string Name { set; get; }
}
Now in your GET action, you will create an object of the ShoppingCartViewModel, load the CartItems property and send to the view.
public ActionResult Index()
{
var cart = new ShoppingCartViewModel
{
CartItems = new List<Product>
{
new Product { Id = 1, Name = "Iphone" },
new Product { Id = 3, Name = "MacBookPro" }
},
TotalPrice = 3234.95
};
return View(cart);
}
Now i will create an EditorTemplate. To do that, Go to your ~/Views/YourControllerName folder, and Create a directory called EditorTemplates and add a view with name Product.cshtml
The name of the file should match with the name of the type.
Open this new view and add the below code.
#model YourNamespace.Product
<div>
<h4>#Model.Name</h4>
#Html.HiddenFor(s=>s.Id)
</div>
You can keep the display however you want. But the important thing is, We need to keep a form field for the productId. We are keeping that in a hidden field here.
Now let's go back to our main view. We need to make this view strongly typed to our ShoppingCartViewModel. We will use the EditorFor html helper method in this view to call our editor template
#model ReplaceYourNamespaceHere.ShoppingCartViewModel
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.CartItems)
<p>Total : #Model.TotalPrice</p>
<input type="submit" />
}
And in your HttpPost action method, We will have a paramer of type ShoppingCartViewModel. When the form is submitted, MVC Model binder will map the posted form values to an object of ShoppingCartViewModel.
[HttpPost]
public ActionResult Index(ShoppingCartViewModel model)
{
foreach (var item in model.CartItems)
{
var productId = item.Id;
// to do : Use productId and do something
}
return RedirectToAction("OrderSucessful");
}
You can iterate through the CartItems collection and get the Id of the Products and do whatever you want.
If you wan't to allow the user to edit the items (using a check box) in this page, Take a look at this answer. It is basically same, but you add a boolean property to Product class and use that for rendering a checkbox.
I have a model in my ASP.NET MVC application:
public class SearchArrayModel
{
public long ID { get; set; }
public string Name { get; set; }
public struct AttribStruct
{
public string AttribName { get; set; }
public string[] AttribValues { get; set; }
}
public AttribStruct[] AttribStructTable { get; set; }
}
In controller I'm filling it by some data from WebAPI (filling process is okay), I created an array of SearchArrayModel because I have a lot of items to fill from webAPI (It's a webAPI from site similar to ebay), for example some phones with its names, and attributes which u normally see on the auction site).
SearchArrayModel[] src = new SearchArrayModel[x];
{
//filling the fields
}
And on the end of the ActionResult I have:
return View(src);
//Visual Studio tells me that it is a "SearchArrayModel[] src"
I have also View, where I want to get and display the data:
#model allegrotest.Models.SearchArrayModel
#using (Html.BeginForm())
{
<h2>#Model.AttribStructTable[1].AttribName</h2>
<h3>#Model.AttribStructTable[1].AttribValues[1]</h3>
//indexes of arrays are just for testing, if all will be good I will write a loop
}
But when I'm starting the app I have an error:
The model item passed into the dictionary is of type
'allegrotest.Models.SearchArrayModel[]', but this dictionary requires
a model item of type 'allegrotest.Models.SearchArrayModel
I know that this is a complex array and I don't know how to pass this array from Controller to View.
I tried to write in View:
#model allegrotest.Models.SearchArrayModel[]
but then I can't get into the fields inside the #Model
Starting from assumption that "filling process is okay" is wrong.
Note: I made this assumption because I see that you are not interested in Model[index] and I noticed in SearchArrayModel[x]; { } the ;.
SearchArrayModel src = new SearchArrayModel
{
AttribStructTable = new SearchArrayModel.AttribStruct[]
{
new SearchArrayModel.AttribStruct{AttribName = "0Nume", AttribValues = new []{"0one", "0two"}},
new SearchArrayModel.AttribStruct{AttribName = "1Nume", AttribValues = new []{"1one", "1two"}},
},
Name = "SearchArrayName"
};
Your View is okay and is working
#model allegrotest.Models.SearchArrayModel
#using (Html.BeginForm())
{
#foreach(var attribStruct in #Model.AttribStructTable)
{
<h2>#attribStruct.AttribName</h2>
#foreach(var attribValue in attribStruct.AttribValues)
{
<h3>#attribValues</h3>
}
}
}
Another solution will be to make the modelof View to be an IEnumerable and in the Action you can make return View(src.ToList());
Also I noticed, when I tested your code, that you have Model.AttribStructTable which is wrong because your Model is a collection and you have to specify which element from model you want to display Model[index] (not posible with IEnumerable), Model.First() or you can iterate through collection.
#model IEnumerable<allegrotest.Models.SearchArrayModel>
#using (Html.BeginForm())
{
#foreach(var attribStruct in #Model.First().AttribStructTable)
{
<h2>#attribStruct.AttribName</h2>
#foreach(var attribValue in attribStruct.AttribValues)
{
<h3>#attribValues</h3>
}
}
}
If you iterate through all items from Model will look like this
#model IEnumerable<allegrotest.Models.SearchArrayModel>
#using (Html.BeginForm())
{
#foreach(var searchArrayModel in Model)
{
#foreach(var attribStruct in #searchArrayModel)
{
<h2>#attribStruct.AttribName</h2>
#foreach(var attribValue in attribStruct.AttribValues)
{
<h3>#attribValues</h3>
}
}
}
}
#model allegrotest.Models.SearchArrayModel[]
which is an array. So you could try
#foreach (SearchArrayModel item in Model)
{
<h2>#item.AttribStructTable[1].AttribName</h2>
<h3>#item.AttribStructTable[1].AttribValues[1]</h3>
..
}
or
#for (int i = 0; i < Model.Length; ++i)
{
<h2>#Model[i].AttribStructTable[1].AttribName</h2>
<h3>#Model[i].AttribStructTable[1].AttribValues[1]</h3>
..
}
I wanted to get invoice items from the database,But there's a problem in IEnumerable Type
Error
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.InvoiceHD_19624A0A21E23E6589B4A75F4B214A34A6186F3A2FF588A6B9CC2A40272A9BBD', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ICSNew.Data.InvoiceHD]'.
My Controller
public ActionResult GetInvoice(int Id)
{
Models.InvoiceHDViewModel _invHd = new Models.InvoiceHDViewModel();
ICSNew.Data.InvoiceHD _invOdr = new Data.InvoiceHD();
_invOdr = (new ICSNew.Business.ICSNewController.SalesController())
.GetInvoiceItemByInvoiceId(Id);
_invHd.Cash = _invOdr.CashAmount;
return View(_invOdr);
}
My View
#model IEnumerable<ICSNew.Data.InvoiceHD>
#{
Layout = null;
}
<h2>GetInvoice</h2>
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item.CashAmount)
}
My Repository
public InvoiceHD GetInvoiceItemByInvoiceId(int InvoiceId)
{
try
{
return context.InvoiceHDs.Where(x => x.InvoiceId == InvoiceId
&& x.IsActive == true).FirstOrDefault();
}
catch (Exception ex)
{
return new InvoiceHD();
}
}
Since you pass an instance of InvoiceHD to the view, you need to change the model as InvoiceHD and remove the foreach block in your view code as below
#model ICSNew.Data.InvoiceHD
#{
Layout = null;
}
<h2>GetInvoice</h2>
#Html.DisplayFor(m => m.CashAmount)
As the error is trying to tell you, you declared your view as taking a collection (IEnumerable<>) of objects, but you tried to pass it a single object instance.
That won't work.
I am new in ASP.NET MVC.
I have a problem like below.
In Controller i have a code like this.
var students= db.Sagirdler.Where(x => x.SinifID == sinif.SinifID).
Select(m => new {m.Name, m.Surname}).ToList();
TempData["Students"] = students;
return RedirectToAction("Index", "MyPage");
This is my Index Action in MyPageController where I redirect and i call View.
public ActionResult Index()
{
ViewBag.Students = TempData["Students"];
return View();
}
And in View I use this code.
#{
ViewBag.Title = "Index";
var students = ViewBag.Students;
}
#foreach (var std in students)
{
#std.Name
<br/>
}
It says:
'object' does not contain a definition for 'Name'
What is the problem? How can I solve it?
You want to use
ViewBag.Students = students;
instead of TempData.
What I think you're trying to achieve would be better implemented like so:
Create a class
public class StudentViewModel
{
public string Name { get;set;}
public string Surname {get;set;}
}
then in your view using
#model IEnumerable<StudentViewModel>
#foreach (var student in Model)
{
...
}
And in your controller
var students = db.Sagirdler.Where(x => x.SinifID == sinif.SinifID)
.Select(m => new StudentViewModel { Name = m.Name, Surname = m.Surname} )
.ToList();
return View(students);
I'm trying to pass an array from my controller to my view using my Model. My method does not work for some reason. I've posted it below.
Controller:
public ActionResult Confirmation()
{
string[] Array = new string[2] {"Pending", "07/07/2013"};
ConfirmationModel Con = new ConfirmationModel
{
Status = Array[0],
AppDate = Array[1],
};
return View();
}
Model:
public class ConfirmationModel
{
public string Status { get; set; }
public string AppDate { get; set; }
}
View:
#model site.ConfirmationModel
#{
ViewBag.Title = "Confirmation";
}
#Html.DisplayFor(Mode => Model.Status)
#Html.DisplayFor(Mode => Model.AppDate)
You aren't passing your model to your view. Change the line below:
return View();
To this;
return View(Con);
You haven't actually included the model in the result. Do this:
return View(Con);
You should return populated model to your view. In your case:
return view(con)
Then use con in your view.
You're not passing any model to the view to be rendered.
The View() method has an overload to receive an object model to render in the view.
Try this: return View(Con);