简体   繁体   中英

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"

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.

把它放在ViewData中,并使用for..each循环它?

Look at this link: http://nerddinnerbook.s3.amazonaws.com/Part6.htm

Basically you could load the array into a viewdata object, and use that as you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM