简体   繁体   中英

Fill Dropdownlist with values from database - MVC4

i have a table in my database which i select all rows to fill it in my dropdownlist in my view.

i can´t understand how can i fill the values in there.

someone can give me a hand?

My code:

Model:

public class MyList
    {
        public int id { get; set; }
        public string name{ get; set; }
    }

    public class Empresas
    {
        public static IEnumerable<MyList> Getmyinformation()
        {
            var list = new List<MyList>();
            string connection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            using (var con = new SqlConnection(connection))
            {
                con.Open();
                using (var command = new SqlCommand("SELECT * FROM mytable", con))
                {
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        string Name= reader[1] as string;
                        list.Add(new MyList() { name= Name});
                    }
                }
                con.Close();
            }
            return list;
        }
    }

    public class DefaultConnection : DbContext
    {
       public DbSet<MyList> lat { get; set; }  
    }

Controller:

private DefaultConnection db = new DefaultConnection();
 public ActionResult Add()
        {
            return View(db.lat.ToList());
        }

View:

@Html.DropDownListFor("-- Select --", new SelectList("")) <=== ???? i dont know

Simply in controller type:

ViewBag.CategoryList = new SelectList(db.Categories.ToList(), "Id", "Name");

And in view write:

@Html.DropDownListFor(model => model.CategoryId, ViewBag.CategoryList as IEnumerable<SelectListItem>, new { @class = "anyclass" })

In my practice I create dropdownlist as follow:

first I create view model

public class MyObj
{
    public int id { get; set; }
    public string name{ get; set; }
}
// viewmodel
public class MyviewModel
{
    public IQuerable<MyObj> MyObjs{get;set;}
    public Other Other{get;set;}
}

then I pass this model from controller to view

private DefaultConnection db = new DefaultConnection();
public ActionResult Index()
{
    var drop = new MyviewModel 
    {
        MyObjs = db.MyObjs,// selecting table...
        Other = new Other
    }
    return View(drop);
}

in Controller

 @Html.DropDownListFor(model => model.Other.MyObjId, new SelectList(Model.MyObjs , "id", "name","--select--"))

Create a ViewModel like this:

public class ListViewModel
{
    public MyList MyList { get; set; }
    public int SelectedId { get; set; }
}

Then, change your Action to this:

public ActionResult Add()
{
    var viewModel = new ListViewModel { MyList = db.lat.ToList() };
    return View(viewModel);
}

And, then, this is what you will have in your View:

@model MyApp.ViewModels.ListViewModel

@Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.MyList as IEnumerable, "Id", "Name"))

Try this,

View :-

@Html.DropDownListFor(m => m.CustomerId, Model.customerNameList, "--Select--")

Controller:-

public ActionResult CustomerInfo()
        {

            var List = GetCustomerName();
            ViewBag.CustomerNameID = new SelectList(List, "CustomerId", "customerName");
            ViewBag.RegisterItems = GetAllRegisterData();
            return View();
        }

public List<CustomerModel> GetCustomerName()
        {
            // Customer DropDown
            using (dataDataContext _context = new dataDataContext())
            {
                return (from c in _context.Customers
                        select new CustomerModel
                        {
                            CustomerId = c.CID,
                            customerName = c.CustomerName
                        }).ToList<CustomerModel>();
            }
        }

Model:

 public class CustomerModel
    {
        public int CustomerId { get; set; }

        [StringLength(9), Required, DisplayName("Social security number")]
        [RegularExpression(@"\d{3}-\d\d-\d{4}", ErrorMessage = "Invalid social security number")]
        public string customerName { get; set; }

        public List<MyListItems> customerNameList { get; set; }
}

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