Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC how to bind custom model to view

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"

like image 935
Smallville Avatar asked Sep 14 '25 14:09

Smallville


1 Answers

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.

like image 156
MunkiPhD Avatar answered Sep 17 '25 03:09

MunkiPhD