ASP.NETMVC应用程序中的视图没有显示来自MySQL数据库的数据。
创始人
2024-09-19 08:00:29
0
  1. 确认MySQL数据库已连接并包含数据表。
  2. 在Model文件夹中创建一个名为MySqlContext.cs的类,该类继承自DbContext类。在该类的构造函数中,使用数据库连接字符串通过DbConnection数据库工厂创建一个MySqlConnection实例。代码示例:
using System.Data.Common;
using System.Data.Entity;
using MySql.Data.Entity;

namespace YourAppName.Models
{
    public class MySqlContext : DbContext
    {
        public MySqlContext() : base(CreateConnection(), true)
        {
        }

        private static DbConnection CreateConnection()
        {
            var connString = "your mysql connection string here";
            var factory = new MySqlConnectionFactory();
            return factory.CreateConnection(connString);
        }
    }
}
  1. 在Models文件夹下创建一个名为DataModel.cs的类,用于表示MySQL数据库中的数据表。在该类中定义数据表的模型,如下所示:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace YourAppName.Models
{
    [Table("YourTableName")]
    public class DataModel
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        // Add more properties here as needed.
    }
}
  1. 在Controller中创建一个MySqlContext实例,从MySqlContext中获取数据。代码示例:
using System.Linq;
using System.Web.Mvc;
using YourAppName.Models;

namespace YourAppName.Controllers
{
    public class MyController : Controller
    {
        private readonly MySqlContext db = new MySqlContext();

        public ActionResult Index()
        {           
            var dataModels = db.Set().ToList();
            return View(dataModels);
        }
    }
}
  1. 在View中使用Razor语法,遍历数据并显示在视图中。示例代码:
@model IEnumerable
@foreach (var dataModel in Model)
{
    

@dataModel.Id - @dataModel.Name

}

通过以上步骤,您应该可以成功地在ASP.NET MVC应用程序中从MySQL数据库中获取数据并在视图中显示。

相关内容

热门资讯

解密透视!哈糖大菠萝可以开挂吗... 解密透视!哈糖大菠萝可以开挂吗,模拟器打开hhpoker,教材教程(确实有挂)-哔哩哔哩哈糖大菠萝可...
揭幕透视!约局吧德州透视,po... 揭幕透视!约局吧德州透视,pokemmo脚本辅助下载,经验教程(真是有挂)-哔哩哔哩pokemmo脚...
总结透视!pokermaste... 您好,pokemomo辅助软件这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
详情透视!we poker免费... 详情透视!we poker免费辅助器,wepoker有用吗,模板教程(有挂秘籍)-哔哩哔哩1、实时w...
开挂透视!wejoker私人辅... 开挂透视!wejoker私人辅助软件,epoker有透视吗,攻略教程(有挂透视)-哔哩哔哩1)wej...
揭幕透视!hhpoker是真的... 揭幕透视!hhpoker是真的吗,wepoker辅助软件价格,妙招教程(有挂方法)-哔哩哔哩1、全新...
揭幕透视!破解辅助插件wepo... 揭幕透视!破解辅助插件wepoker,wepoker买脚本靠谱吗,技法教程(的确有挂)-哔哩哔哩1、...
总结透视!pokemmo脚本手... 总结透视!pokemmo脚本手机版,德州透视hhpoker,大纲教程(有挂方针)-哔哩哔哩1、该软件...
必备透视!wepoker一直输... 必备透视!wepoker一直输的号能继续打吗,hhpoker是真的还是假的,妙招教程(确实有挂)-哔...
揭幕透视!hhpoker的辅助... 揭幕透视!hhpoker的辅助是真的吗,fishpoker透视底牌,绝活教程(有挂助手)-哔哩哔哩小...