Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

asp.net mvc - How to Populate DropDownList from the Database in MVC

I am new to ASP NET MVC

I need Populate a drop down list from values obtained from a database table using MySql database and view model, after checking if the current user is application enabled, using ASP NET MVC.

This is the tutorial

My code below return

Error: returns void, a return keyword must not be followed by an object expression

On this line

return items; 

Any help really appreciated.

Controller

public ActionResult Recovery()
{
      try
        {
            string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
    
            using (var connection =
                new MySqlConnection(cs))
            {
                string commandText = " SELECT cCountry FROM `dotable_user` " +
                    " WHERE cName = @Username; ";
    
                using (var command =
                    new MySqlCommand(commandText, connection))
                {
                    if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name.ToString()))
                    {
                        command.Parameters.AddWithValue("@Username", HttpContext.User.Identity.Name.ToString());
                    }
    
                    connection.Open();
    
                    string cCountry = (string)command.ExecuteScalar();
    
                    if (String.IsNullOrEmpty(cCountry))
                    {
                        TempData["Message"] = "No user.";
                        ViewBag.Message = String.Format("No user.");
                    }
    
    
                    List<SelectListItem> items = new List<SelectListItem>();
                    using (MySqlConnection con = new MySqlConnection(cs))
                    {
                        string query = " SELECT cCountry FROM `dotable_countries` " +
                            " WHERE cCountry = '" + cCountry.ToString() + "' ";
    
                        using (MySqlCommand cmd = new MySqlCommand(query))
                        {
                            cmd.Connection = con;
                            con.Open();
                            using (MySqlDataReader sdr = cmd.ExecuteReader())
                            {
                                while (sdr.Read())
                                {
                                    items.Add(new SelectListItem
                                    {
                                        Text = sdr["cCountry"].ToString(),
                                        Value = sdr["cCountry"].ToString()
                                    });
                                }
                            }
                            connection.Close();
                        }
                    }
    
                    return items;                        
                }
            }
        }
        catch (Exception ex)
        {
            TempData["Message"] = "Login failed.Error - " + ex.Message;
        }
}

Update

I have tried with this code.

I have error

Error CS0103 The name 'cCountry' does not exist in the current context

  public ActionResult Recovery()
  {
      try
        {
            string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
    
            using (var connection =
                new MySqlConnection(cs))
            {
                string commandText = " SELECT cCountry FROM `dotable_user` " +
                    " WHERE cName = @Username; ";
    
                using (var command =
                    new MySqlCommand(commandText, connection))
                {
                    if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name.ToString()))
                    {
                        command.Parameters.AddWithValue("@Username", HttpContext.User.Identity.Name.ToString());
                    }
    
                    connection.Open();
    
                    string cCountry = (string)command.ExecuteScalar();
    
                    if (String.IsNullOrEmpty(cCountry))
                    {
                        TempData["Message"] = "No user.";
                        ViewBag.Message = String.Format("No user.");
                    }   

                    TempData["Dates"] = PopulateDates();                 
                }
            }
        }
        catch (Exception ex)
        {
            TempData["Message"] = "Login failed.Error - " + ex.Message;
        }
   }


        private static List<SelectListItem> PopulateDates()
        {
            List<SelectListItem> items = new List<SelectListItem>();
            string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString; 
            
            using (MySqlConnection con = new MySqlConnection(cs))
            {
                string query = " SELECT cCountry FROM `dotable_countries` " +
                    " WHERE cCountry = '" + cCountry.ToString() + "'; ";

                using (MySqlCommand cmd = new MySqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (MySqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            items.Add(new SelectListItem
                            {
                                Text = sdr["cCountry"].ToString(),
                                Value = sdr["cCountry"].ToString()
                            });
                        }
                    }

                    cmd.Connection.Close();
                }
            }

            return items;
        }
question from:https://stackoverflow.com/questions/65898133/how-to-populate-dropdownlist-from-the-database-in-mvc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are not passing cCountry value to populateDates.That's why you are getting this error. You can do something like below to get drop down populated. However it is not good idea to write Business Logic directly in controller. You should move it to model or Business layer.

private static List<SelectListItem> PopulateDates(string country)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString; 
            
            using (MySqlConnection con = new MySqlConnection(cs))
            {
                string query = " SELECT cCountry FROM dotable_countries WHERE cCountry = @country";

                using (MySqlCommand cmd = new MySqlCommand(query))
                {
                   cmd.Parameters.AddWithValue("@country",country);
                    cmd.Connection = con;
                    con.Open();
                    using (MySqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            items.Add(new SelectListItem
                            {
                                Text = sdr["cCountry"].ToString(),
                                Value = sdr["cCountry"].ToString()
                            });
                        }
                    }

                    cmd.Connection.Close();
                }
            }

            return items;
        }

and while calling this method in Action pass country value to it like below

TempData["Dates"] = PopulateDates(cCountry);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...