我使用 Web 表单开发网站,现在我有一个项目,我使用 MVC3 框架和 Rzor。我的问题是关于 MVC 中的一些基本设计模式。我有一个网页,在左侧我将从 SQL 表中提取类别,在中心我将查询另一个 Sql 表,整个页面上还有一些其他内容。
所以我的问题是......将数据引入一个网页的最佳方式是什么,所有这些查询都是完全独立的,我是否需要为每个查询创建新的模型?或者有更好的方法吗?
在 WebForms 中,我使用了用户控件,其中每个用户控件都有自己的设计和 Sql 查询。我听说过在 MVC 中使用部分 View ,但我不确定,我想我很难理解如何使用不同的查询将数据引入一个网页并在网页上显示输出。
谢谢
最佳答案
您应该创建一个ViewModel
。 查看下面的更新
这是代表您的页面的模型。您想要在 View 中显示的元素应该存在于您的 ViewModel 中。您将在 Controller 中填充 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;}
}
在你的 Controller 中:
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;
}
}
然后在您的 View 中适本地显示它:
@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>
<小时/>
更新
这是关于您的评论,您提到您的数据库表和列定期更改。
我不能肯定地说,但也许你不应该每天都这样制作表,也许你可以有更好的数据库设计,或者也许 RDBMS 不适合你,你应该看看进入 NoSql 数据库(如 MongoDB )
尽管如此,如果您继续使用上面的代码,我建议将其放入其自己的数据层类中。
另请查看Dapper它是一个非常薄的数据访问层,仅通过 SQL 查询或存储过程从数据库获取对象。 (正是您所需要的)它是由 stackoverflow 制作和使用的。
关于asp.net mvc 和 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12233746/