我是MVC的新手,来自一个经典的ASP商店。 我们习惯于编写自己的SQL选择来将信息拉入asp页面。 我正在尝试在 MVC 中找到类似的方法来执行此操作,我在我尝试遵循 asp.net mvc 和 sql 查询中找到了一个示例。
我想我理解了大部分内容,但我挂断了以下内容: 将数据转换为字符串[]并返回。
任何人都可以为我扩展这一点或给我其他例子吗?
我试图完成的是从表中提取数据并在我的视图中创建一个树视图。
class MainPageViewModel
{
//this data is from a different table.
//and goes on the left of the page
public string Categories {get; set;}
//this data is also from a different table.
//and goes on the center of the page
public List<Products> Products {get; set;}
}
控制器:
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
MainPageViewModel vm = new MainPageViewModel();
vm.Categories = GetCategories();
//use the GetProducts() to get your products and add them.
vm.Products.Add(...);
return View(vm); //pass it into the page
}
string[] GetCategories()
{
DataTable data = GetDataFromQuery("SELECT * FROM Categories WHERE..");
//convert the data into a string[] and return it..
}
//maybe it has to return something else instead of string[]?
string[] GetProducts()
{
DataTable data = GetDataFromQuery("SELECT * FROM Products WHERE..");
//convert the data into a string[] and return it..
}
DataTable GetDataFromQuery(string query)
{
SqlDataAdapter adap =
new SqlDataAdapter(query, "<your connection string>");
DataTable data = new DataTable();
adap.Fill(data);
return data;
}
}
你没有写 sql 代码。您可以使用 Linq to Sql 轻松实现。只需将解决方案linq添加到sql类中即可。然后,您将添加数据库,并且无需SQL代码即可连接数据库。