搜索框表ado.net

时间:2016-04-18 19:28:02

标签: c# asp.net asp.net-mvc ado.net

我正在尝试通过ADO.NET提取搜索框功能

到目前为止,我有一个观点:

@using (Html.BeginForm())
{
    <p>
        Find Pokemon: @Html.TextBox("searchKey")
        <input type="submit" value="Search" />


    </p>
}


@foreach (var item in Model){...

有效。 然后我有控制器:

    public ActionResult NoEF(string searchKey)
    {
        Pokemon poke = new Pokemon();

            poke.Search(searchKey);
        //poke.Search(poke.Poke_Name, poke.Poke_Color);

        return View(poke);

    }

应该重定向到Pokemon.cs文件。它有一个类应该连接到数据库,执行查询,然后根据在搜索框中键入的信息显示信息,如下所示:

 public List<Pokemon> Search(string searchKey)
        {
            List<Pokemon> pokemons = new List<Pokemon>();


            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename = 'C:\Users\Pokedatabase.mdf'; Integrated Security = True");

            //Default order by name
            string query = "SELECT        Pokemon.*, Poketype.* FROM Pokemon INNER JOIN" +
                           "  Poketype ON Pokemon.P_Type = Poketype.Type_Id" +
                            " Where Pokemon.Poke_Name = '"+ searchKey + "' || Poke_Color = '"+ searchKey + "' order by Poke_Name";

            //Opens up a connection to the database
            con.Open();

我的问题是,在打开连接后,我不太确定要放在哪里。我到处搜索了。到目前为止,我使用的YOLO代码显然不起作用:

    using (SqlCommand cmd = new SqlCommand(query, con))
    {
        //Creates a data reader object and supplies it with data
        SqlDataReader dr = cmd.ExecuteReader();

        try
        {
            con.Open();
            while (dr.Read())
            {
                dr = dr(dr.GetValue(0) + " - " + dr.GetValue(1) + " - " + dr.GetValue(2));
            }
            dr.Close();
            cmd.Dispose();
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Can not open connection ! ");
        }

    }

    return pokemons;
}

有任何改进建议吗?我完全迷失了。

1 个答案:

答案 0 :(得分:0)

创建一类口袋妖怪,如:

    public class Pokemon
    {
      public string Name{get;set;}
      public string Type{get;set;}
    }

你可以在数据中添加你喜欢的任何属性,我只拿了两个属性作为帮助。 比你的搜索功能更喜欢这样:

        con.open();

        sqlDs = new DataSet();
        conOpen();
        var sqlComm = new SqlCommand();
        sqlComm.Connection = con;
        sqlComm.CommandType = CommandType.Text;
        sqlComm.CommandText = query;
        sqlDa = new SqlDataAdapter(sqlComm);
        sqlDa.Fill(sqlDs);
        conClose();
        var dt = new DataTable();
        dt = sqlDs.Tables[0];

现在,在此之后填充Pokemon类型列表:

        var list = (from a in dt
                    select new Pokemon
                    {
                        Name = a.Name,
                        Type = a.Type
                    }).ToList();

            return list;

将此列表返回给搜索功能

中的控制器