加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net mvc和sql查询

发布时间:2020-12-16 06:31:41 所属栏目:asp.Net 来源:网络整理
导读:我使用网络表单开发网站,现在我有一个项目,我使用Rzor MVC3框架.我的问题是关于MVC中的一些基本设计模式.我有一个网页,在左侧我将从SQL表中拉出类别,在中心我将查询另一个Sql表,以及整个页面上的更多. 所以我的问题是……什么是将数据引入一个网页的最佳方式
我使用网络表单开发网站,现在我有一个项目,我使用Rzor MVC3框架.我的问题是关于MVC中的一些基本设计模式.我有一个网页,在左侧我将从SQL表中拉出类别,在中心我将查询另一个Sql表,以及整个页面上的更多.

所以我的问题是……什么是将数据引入一个网页的最佳方式,所有这些查询完全独立,我是否需要为每个查询创建新的模型?或者有更好的方法吗?

在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;}
}

在你的控制器中:

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;
    }  
}

然后在您的视图中显示它:

@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制作和使用的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读