如何在MVC 3中从数据库检索数据 [英] How to retrieve data from database in mvc 3
本文介绍了如何在MVC 3中从数据库检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我放在了Index.cshtml
中的一个表中. (MVC 3剃刀视图).
现在,我想添加以下代码以从数据库检索数据并填写表格.
该代码放在哪里?
是否将其放在index.cshtml
或homeController.cs
或其他位置?
I dropped in a table in Index.cshtml
. ( MVC 3 razor view).
Now I want to add the following code to retrieve the data from the database and fill the table.
Where do I put this code?.
Do I put it in index.cshtml
or homeController.cs
or where else?
string s=ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sel = "select * from TableName";
SqlConnection con = new SqlConnection(s);
SqlCommand cmd = new SqlCommand(sel, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
推荐答案
由于逻辑是获取数据,因此必须与MVC模式的Model
部分保持一致.要进一步阅读,请了解模型,视图和控制器(C#) [^ ]
Since the logic is fetch data, it has to go with the Model
part of MVC pattern. For further read Understanding Models, Views, and Controllers (C#)[^]
MVC模式是关于分离组件的,所以您不会向视图添加数据访问权限.
也许这会帮助 ASP.NET MVC 3模型和数据访问 [
The MVC pattern is about separating components so no you would not add your data access to the view.
Perhaps this will help ASP.NET MVC 3 Models and Data Access[^]
这篇关于如何在MVC 3中从数据库检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文