hig*_*ers 4 sql asp.net asp.net-mvc asp.net-mvc-3
我使用网络表单开发网站,现在我有一个项目,我使用Rzor MVC3框架.我的问题是关于MVC中的一些基本设计模式.我有一个网页,在左侧我将从SQL表中拉出类别,在中心我将查询另一个Sql表,以及整个页面上的更多.
所以我的问题是......什么是将数据引入一个网页的最佳方式,所有这些查询完全独立,我是否需要为每个查询创建新的MODEL?或者有更好的方法吗?
在WebForms中,我使用了用户控件,其中每个用户控件都有自己的设计和Sql查询.我听说过在MVC中使用部分视图,但我不确定,我想我很难理解如何使用不同的查询和在网页上显示输出将数据导入一个网页.
谢谢
你应该创建一个ViewModel.请看下面的更新
这是代表您的页面的模型.要在视图中显示的元素应存在于ViewModel中.您将在控制器中填充ViewModel并在页面上显示它们.
我写了一个购物网站页面的例子,左边是分类,中间是产品.两个实体都存在于不同的表中.
例:
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;}
}
Run Code Online (Sandbox Code Playgroud)
在你的控制器中:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的视图中显示它:
@model MainPageViewModel
@{ ViewBag.Title = "MainPage"; }
<div id="left-bar">
<ul>
@foreach (var category in Model.Categories)
{
<li>@category</li>
}
</ul>
</div>
<div id="center-content">
<ul>
@foreach (var product in Model.Products)
{
<li>@product.Name</li>
<li>@product.Price..</li>
.....
}
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
更新
这是关于您提到您的数据库表和列定期更改的注释.
我不能肯定地说,但也许你不应该每天都像这样制作表格,也许你可以拥有更好的数据库设计,或者RDBMS对你来说不是正确的,你应该看看NoSql数据库(如MongoDB)
然而,如果你继续上面的代码,我建议将它放入自己的数据层类中.
另外看看Dapper它是一个非常瘦的数据访问层,它只使用sql查询或存储过程从数据库中获取对象.(正是你需要的)它是由stackoverflow制作和使用的.
| 归档时间: |
|
| 查看次数: |
18278 次 |
| 最近记录: |