运行IIS Express时视图返回"0"的技术问题求助
问题解决:在MVC表格中展示tLoyalty表的LoyaltyID数据
核心问题分析
- 控制器未查询数据库:
LoyaltyQuery方法仅实例化了单个tLoyalty对象,而非从数据库获取数据集。int类型的LoyaltyID默认值为0,所以页面返回"0"。 - 视图绑定错误:循环中试图访问
@query.tLoyalty,但模型是tLoyalty实体,应直接访问LoyaltyID属性;且视图未声明接收的模型类型。 - 缺少DbContext实例:未使用ADO.NET Entity Data Model生成的
DbContext来连接数据库执行查询。
修正步骤
1. 确认DbContext类存在
确保项目中有自动生成的DbContext类(假设名为Web3Context),包含对应的数据集合:
using System.Data.Entity; public class Web3Context : DbContext { public Web3Context() : base("name=Web3Context") // 连接字符串名需匹配web.config配置 { } public DbSet<tLoyalty> tLoyalty { get; set; } }
2. 修正控制器代码
修改LoyaltyQuery方法,通过DbContext查询数据库并传递数据到视图:
using Web3.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Web3.Models; namespace Web3.Controllers { public class LoyaltyController : Controller { public ActionResult Index() { return View(); } public ActionResult LoyaltyInfo() { return View(); } public ActionResult LoyaltyQuery() { using (var context = new Web3Context()) { // 查询所有tLoyalty记录 var loyaltyData = context.tLoyalty.ToList(); // 将数据集传递给视图 return View(loyaltyData); } } } }
3. 修正视图代码
在视图顶部声明模型类型,并正确遍历显示LoyaltyID:
@model IEnumerable<tLoyalty> <div> <table class="table table-bordered table-hover"> <thead> <tr> <th>Loyalty ID</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @item.LoyaltyID </td> </tr> } </tbody> </table> </div>
4. 验证数据库连接字符串
确保web.config中存在正确的连接字符串,名称与DbContext构造函数一致:
<connectionStrings> <add name="Web3Context" connectionString="Data Source=你的SQL服务器地址;Initial Catalog=你的数据库名;Integrated Security=True;" providerName="System.Data.SqlClient" /> </connectionStrings>
完成以上修改后,访问Loyalty/LoyaltyQuery路径,页面会从数据库读取所有tLoyalty记录,并在表格中逐行显示LoyaltyID值。
内容的提问来源于stack exchange,提问作者mole7
相关产品推荐
相关产品推荐

