muco
muco

Reputation: 275

select multiple entities from database in asp.net mvc

I try to take gender entities(male or female) from database and I want to show it in dropdown box:

Controller:

List<Gender> list2 = db.Gender.ToList();
ViewBag.GenderList = new SelectList(list2, "GenderID", "GenderType");

View:

@Html.DropDownListFor(model => model.GenderID, ViewBag.GenderList as SelectList,"--select--",new { @class="form-control"})

Where is my fault ? I need help

Gender Class

public class GenderViewModel
{
    public int GenderID { get; set; }
    public string GenderN { get; set; }
}

Personal Class

public class PersonalViewModel
{
    public int PersonalID { get; set; }
    public string PName { get; set; }
    public string PLastname { get; set; }
    public System.DateTime DOB { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string PPassword { get; set; }
    public int GenderID { get; set; }
    public int PAuthorisation { get; set; }
    public bool PStatus { get; set; }
    public int ShopId { get; set; }
    public System.DateTime JobStartDate { get; set; }

    public string GenderType { get; set; }
    public string ShopName { get; set; }
}

Upvotes: 0

Views: 334

Answers (3)

Brian Mains
Brian Mains

Reputation: 50728

Your Gender class has GenderN (I presume GenderName?) but is binding to GenderType, so that mismatch alone will cause an exception. ViewBag is dynamic, so you shouldn't need the cast in the view (since it's evaluated at runtime)...

Change GenderClass:

public class GenderViewModel
    {
        public int GenderID { get; set; }
        public string GenderName { get; set; }
    }

And change controller:

ist<Gender> list2 = db.Gender.ToList();
ViewBag.GenderList = new SelectList(list2, "GenderID", "GenderName");

Posting the specific error will help.

Upvotes: 1

Ronen Rimon
Ronen Rimon

Reputation: 21

on html part try: @Html.DropDownList("GenderList", null, "--select--", htmlAttributes: new { @class = "form-control" })

Upvotes: 0

scgough
scgough

Reputation: 5252

Not sure of the exact error you're seeing but I'm sure you can use a ViewBag in-place like that as it is an anonymous object. Assign the ViewBag to a separate variable:

@{
   var genderlist = (SelectList)ViewBag.GenderList;
}

@Html.DropDownList("genderID", genderlist, "Gender", new { @class = "classnameifneeded" })

Personally, I would do it like this:

Class/C#/Controller Side:

List<Gender> list2 = db.Gender.ToList();
ViewBag.GenderList = list2;

View Side:

@{
   var genderlist = ViewBag.GenderList;
}

Html.DropDownList("genderID", new SelectList(genderlist, "GenderID", "GenderType", 0), "Gender", new { @class="classnameifneeded" })

Upvotes: 0

Related Questions