简体   繁体   中英

C#: How to Populate a DropDownList with an Object?

I am having some problems. I just created a class named Student which has an other class object which is Batch as

public class Student{
      public Batch batch {get;set;}
      public string Name{get;set;}
      public string CNIC {get;set;}
}

and here is Batch Class

public class Batch {
      public string BatchName {get;set;}
      public int BatchYear {get;set;}
}

and i created a strongly typed view for Student class now how i am supposed to display get Batch Object with User with DropdownListFor method helper. thanks in advance.

The DropDownListFor takes a List<SelectListItem> and turns it into a list. So you need to build the List<SelectListItem> and pass that to your view in your View Model. You won't be able to use a DropDownListFor directly with your batch class.

In order to display a dropdown list of the Batch Class, try something like the following

public class Student{

      public Student()
      {
          BatchSelectList = new List<SelectListItem>();
          BatchSelectList.Add(new SelectListItem { Text = "Some Label", Value = "Some Val" };
      }

      public Batch batch {get;set;}
      public string Name{get;set;}
      public string CNIC {get;set;}

      //Drop down properties used in view
      public String BatchSelectedItem { get; set; }
      public List<SelectListItem> BatchSelectList { get; set; }
}

With the above, you are building a place holder for the item that will be selected in the list, BatchSelectedItem , and you are also building your select list that will be used in the view.

In your view, you will need to the following.

@Html.DropDownListFor(x => x.BatchSelectedItem, Model.BatchSelectList)

Where the first option is what property the select list is bound to, and the second property is the list of objects that populate the DropDownListFor

You can create a list of Batch in your Student model

public class Student{
      public Batch batch {get;set;}
      public string Name{get;set;}
      public string CNIC {get;set;}
      public List<Batch> batchList {get;set;}
}

Then on your model you can set your DropDownList as:

@Html.DropDownListFor(model => model.batch, new SelectList(Model.batchList,"BatchYear","BatchName"))

In the code above you're setting that you have a DDL for batch witch is filled by batchList, shows you BatchName and sets value as BatchYear.

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