LINQ to select data in a list RRS feed

  • Question

  • User417201021 posted


    I am retrieving the list of values from SQL Server table and showing the list values in the dropdownlistfor helper class using ADO.NET.

            public ActionResult Index()
                    mymodel.ShowTimeManagerSet = GetTimeManagerSetsFnctn();
            public List<TimeManagerSetsMdl> GetTimeManagerSetsFnctn()
                List<TimeManagerSetsMdl> TMSetsMdlCmb = new List<TimeManagerSetsMdl>();
                SqlConnection sCn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyCnStringATOM"].ConnectionString);
                SqlCommand sCm = new SqlCommand("Select * from [TimeManagerSetsMdls]",sCn);
                SqlDataAdapter da = new SqlDataAdapter();
                DataSet ds = new DataSet();
                da.SelectCommand = sCm;
                TimeManagerSetsMdl timeManagerSets = new TimeManagerSetsMdl();
                for (int i=0;i<=(ds.Tables["TimeManagerSets"].Rows.Count-1);i++)
                    TMSetsMdlCmb.Add(new TimeManagerSetsMdl { TmeMngrSetKey = i, TimeManagerSet = ds.Tables["TimeManagerSets"].Rows[i][1].ToString(), Category = ds.Tables["TimeManagerSets"].Rows[i][2].ToString() });
                return (TMSetsMdlCmb);
    @Html.DropDownListFor(m => m.SelectedSubProject, new SelectList(Model.ShowTimeManagerSet, "TimeManagerSet", "TimeManagerSet"), "")

    Can you please let me how can i use the LINQ and Entity framework to get the same and save it to the list and show the list values in the dropdownlistfor helper.

    Thank you,

    Jimmit Raval

    Friday, December 14, 2018 10:03 AM

All replies

  • User1724605321 posted

    Hi Jimmit_05,

    You can try to use below codes :


    public ActionResult Index()
                TimeManagerSetsMdl info = new TimeManagerSetsMdl();
                var list = db.TimeManagerSetsMdls.ToList();
                ViewBag.ShowTimeManagerSet = new SelectList(list, "TimeManagerSets", "TimeManagerSets", info.TimeManagerSets);
                return View();

    Model :

    public class TimeManagerSetsMdl
            public int TmeMngrSetKey { get; set; }
            public string TimeManagerSets { get; set; }
            public string Category { get; set; }


    @Html.DropDownListFor(m => m.SelectedSubProject, (IEnumerable<SelectListItem>)ViewBag.ShowTimeManagerSet, "")

    Best Regards,

    Nan Yu

    Monday, December 17, 2018 9:01 AM