表值未显示 - ASP.net

本文关键字:ASP net 显示 | 更新日期: 2023-09-27 17:55:16

这可能是

一个愚蠢的问题,因为我是 asp.net MVC模式的新手。我正在尝试访问数据库中的值,但这些值没有呈现在视图页面上。

这是我编写的代码。

"Resturant"模型的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace OdetoFood.Models
{
    [Table("Resturants")]
    public class Resturant
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public ICollection<ResturantReviews> Reviews { get; set; }
    }
}

这是我的 DbContext 模型:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace OdetoFood.Models
{
    public class OdeToFoodDb : DbContext
    {
        public DbSet<Resturant> Resturants { get; set; }
        public DbSet<ResturantReviews> Reviews { get; set; }
    }
}

控制器类的代码:

public class HomeController : Controller
    {
        OdeToFoodDb _db = new OdeToFoodDb();
        public ActionResult Index()
        {
            var model = _db.Resturants.ToList();
            return View(model);
        }

下面是应该显示值的视图:

@model IEnumerable<OdetoFood.Models.Resturant>
@{
    ViewBag.Title = "Home Page";
 }

@foreach (var item in Model)
{
    <h3>@item.Name</h3>
    <div>@item.City, @item.Country</div>
    <div>@item.Id</div>
}

Web.config 中的连接字符串设置如下:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)'v11.0;AttachDbFilename=|DataDirectory|'aspnet-OdetoFood-20150611025411.mdf;Initial Catalog=aspnet-OdetoFood-20150611025411;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

我在这里做错了什么?

表值未显示 - ASP.net

这将是该项目的种子方法:

protected override void Seed(OdeToFood.Models.OdeToFoodDb context)
    {
        context.Restaurants.AddOrUpdate(r => r.Name,
            new Restaurant { Name = "Sabatino's", City = "Baltimore", Country = "USA" },
            new Restaurant { Name = "Great Lake", City = "Chicago", Country = "USA" },
            new Restaurant
            {
                Name = "Smaka",
                City = "Gothenburg",
                Country = "Sweden",
                Reviews =
                 new List<RestaurantReview>{
                      new RestaurantReview{ Rating = 9, Body="Great Food!" }
                  }
            });
    }