Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 如何在MVC中从数据库填充DropDownList_Asp.net Mvc - Fatal编程技术网

Asp.net mvc 如何在MVC中从数据库填充DropDownList

Asp.net mvc 如何在MVC中从数据库填充DropDownList,asp.net-mvc,Asp.net Mvc,我是新来的ASP.NET MVC 在检查当前用户是否启用了应用程序后,我需要使用MySql数据库和视图模型从数据库表中获得的值填充一个下拉列表,使用ASP NET MVC 这是 我的代码在下面返回 Error: returns void, a return keyword must not be followed by an object expression 在这条线上 return items; 非常感谢您的帮助 控制器 public ActionResult Recovery() {

我是新来的
ASP.NET MVC

在检查当前用户是否启用了应用程序后,我需要使用MySql数据库和视图模型从数据库表中获得的值填充一个下拉列表,使用
ASP NET MVC

这是

我的代码在下面返回

Error: returns void, a return keyword must not be followed by an object expression
在这条线上

return items; 
非常感谢您的帮助

控制器

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;
        }
}
公共操作结果恢复()
{
尝试
{
字符串cs=ConfigurationManager.ConnectionString[“cnj”].ConnectionString;
使用(var)连接=
新的MySQL连接(cs))
{
string commandText=“从'dotable\u user'中选择cCountry”+
“其中cName=@Username;”;
使用(var)命令=
新的MySqlCommand(commandText,connection))
{
如果(!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[“消息”]=“无用户。”;
ViewBag.Message=String.Format(“无用户”);
}
列表项=新列表();
使用(MySqlConnection con=newmysqlconnection(cs))
{
string query=“从'dotable\u countries'中选择cCountry”+
“其中cCountry='”+cCountry.ToString()+”;
使用(MySqlCommand cmd=newmysqlcommand(query))
{
cmd.Connection=con;
con.Open();
使用(MySqlDataReader sdr=cmd.ExecuteReader())
{
while(sdr.Read())
{
items.Add(新建SelectListItem)
{
Text=sdr[“cCountry”]。ToString(),
Value=sdr[“cCountry”]。ToString()
});
}
}
connection.Close();
}
}
退货项目;
}
}
}
捕获(例外情况除外)
{
TempData[“Message”]=“登录失败。错误-”+ex.Message;
}
}
更新

我已经用这个代码试过了

我有错误

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;
        }
错误CS0103当前上下文中不存在名称“cCountry”
公共行动结果恢复()
{
尝试
{
字符串cs=ConfigurationManager.ConnectionString[“cnj”].ConnectionString;
使用(var)连接=
新的MySQL连接(cs))
{
string commandText=“从'dotable\u user'中选择cCountry”+
“其中cName=@Username;”;
使用(var)命令=
新的MySqlCommand(commandText,connection))
{
如果(!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[“消息”]=“无用户。”;
ViewBag.Message=String.Format(“无用户”);
}   
TempData[“Dates”]=PopulateDates();
}
}
}
捕获(例外情况除外)
{
TempData[“Message”]=“登录失败。错误-”+ex.Message;
}
}
私有静态列表填充()
{
列表项=新列表();
字符串cs=ConfigurationManager.ConnectionString[“cnj”].ConnectionString;
使用(MySqlConnection con=newmysqlconnection(cs))
{
string query=“从'dotable\u countries'中选择cCountry”+
“其中cCountry='”+cCountry.ToString()+“;”;
使用(MySqlCommand cmd=newmysqlcommand(query))
{
cmd.Connection=con;
con.Open();
使用(MySqlDataReader sdr=cmd.ExecuteReader())
{
while(sdr.Read())
{
items.Add(新建SelectListItem)
{
Text=sdr[“cCountry”]。ToString(),
Value=sdr[“cCountry”]。ToString()
});
}
}
cmd.Connection.Close();
}
}
退货项目;
}

您没有将cCountry值传递给populateDates。这就是为什么会出现此错误。您可以执行以下操作来填充下拉列表。然而,直接在控制器中编写业务逻辑并不是一个好主意。您应该将其移动到模型层或业务层

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;
        }
私有静态列表填充(字符串国家)
{
列表项=新列表();
圣