Frage

I have a view that makes use of a list and a string value.

Currently I am doing the following and passing it to the view:

var Note = (from p in db.tblNote where p.NoteName = pnote  select  p).ToList();
ViewBag.NotesID = id;

return PartialView(Note);

As you can see, currently I am passing the Note (which is a list) to the View and then will be getting the ViewBag directly in my view.

What I like to do is to create a viewmodel for this. I like to know what the best practice is to create a viewmodel for what I need.

Here is what I came up for the ViewModel :

public class NotesViewModel
{        
    public string NotesID { get; set; } // this will replace where I had ViewBag.NotesID

    public IEnumerable< Notes>  NotesList { get; set; } // this will replace where I had var Note = (from p in db.tblNote      
}

I am somewhat lost on where I create the Notes that you see in IEnumerable<Notes>, do I create another class called Notes in a different .cs file and how do I assign the appropriate type to it. The will represent the the LINQ Query.

War es hilfreich?

Lösung

I assume you want Notes to be a List of type Note? If so then why not just do IEnumerable<Note> ?

A IEnumerable is basically a generic data type that allows you to enumerate over its items, a List an extension of this.

So you would just change your code to be :-

public class NotesViewModel
{        

    public string NotesID { get; set; } // this will replace where I had ViewBag.NotesID

    public IEnumerable<Note>  NotesList { get; set; } // this will replace where I had var Note = (from p in db.tblNote

}

public ActionResult MyFunction()
{
    var Notes = (from p in db.tblNote where p.NoteName = pnote 
            select  p).ToList();

    var oMyNotesVM = new NotesViewModel();
    oMyNotesVM.NotesID = id;
    oMyNotesVM.NotesList = Notes;

    return PartialView(oMyNotesVM );
}

So here all we've done is take the List and passed it to IEnumerable since IEnumerable is a generic form of List. Basically for an item to impliment the IEnumerable it needs to support iteration through its datamembers.. for example

while(enumerator.MoveNext())
{
  object obj = enumerator.Current;
  // work with the object
}

Which is the same (well almost as)

foreach(object obj in collection)
{
    // work with the object
}

If your asking what the datatype for Note should be then that would be the class type of db.tblNote. If this is entity framework then you could just use the class that was auto-generated from your model for this.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top