I would like bind an array data to view in ASP.NET MVC, how can I do that?
sorry for not clear about my question. Right now, I creat a custom object(not array), I tried to pass it to View, but the error shows
"The model item passed into the dictionary is of type 'ContactView' but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable"
You can use the ViewData[], but the best way would be to actually create a view class and return that.
So let's say the view you want to send the data is called Contacts. Create a new View class and return that. so instead of this:
public ActionResult Contacts(){
ViewData["contacts"] = arrayOfContacts[];
...
return View();
}
You can get strongly-typed views by doing this:
public class ContactsView(){
Object[] ContactsList {get;set;}
}
public ActionResult Contacts(){
...
return View(new ContactsView(){
ContactsList = arrayOfContacts[];
});
}
Then in the actual view, you can have it be strongly typed by accepting objects of type ContactsView. That way in the actual View, have it inherit like so:
... Inherits="System.Web.Mvc.ViewPage<ContactsView>" ...
Which allows you to call your array like...
Model.ContactsList
as opposed to this:
object[] arrayOfItems = (Object[])ViewData["theContactsList"];
In which case you'd probably want to check if it's not null, etc. The benefit of this is that if you refactor it's much easier. Not to mention the ease and type security of use of strongly typed objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With