You need to enable JavaScript to run this app. 如何从数据库获取数据存入列表并在index.cshtml中校验两个模型
优惠活动
大模型
产品
解决方案
定价
更多

如何从数据库获取数据存入列表并在index.cshtml中校验两个模型

解决方案

你现有代码中的列表是手动初始化的空对象,没有查询数据库的逻辑,按以下步骤修改即可实现需求:


步骤1:确认数据库上下文(DbContext)配置

确保你的项目中已定义数据库上下文类,且包含两张表对应的DbSet属性,示例:

public class NotificationDbContext : DbContext
{
    // .NET Core版本构造函数,可传入DbContextOptions
    public NotificationDbContext(DbContextOptions<NotificationDbContext> options) : base(options)
    {
    }

    // 两个业务表对应的DbSet
    public DbSet<tbl_notification> tbl_notifications { get; set; }
    public DbSet<tbl_user_notification> tbl_user_notifications { get; set; }
}

.NET Core项目需要在Program.cs/Startup.cs里注册DbContext,示例:

builder.Services.AddDbContext<NotificationDbContext>(options => 
    options.UseSqlServer("你的数据库连接字符串"));

步骤2:修改控制器的Index方法,注入DbContext查询数据

把你原来手动新增空对象的逻辑替换为数据库查询逻辑:

public class HomeController : Controller
{
    private readonly NotificationDbContext _context;

    // 构造函数注入DbContext
    public HomeController(NotificationDbContext context)
    {
        _context = context;
    }

    public ActionResult Index()
    {
        // 从数据库查询两张表的全部数据存入列表
        List<tbl_notification> lstNotifications = _context.tbl_notifications.ToList();
        List<tbl_user_notification> lstUserNotifications = _context.tbl_user_notifications.ToList();

        MainPageModel objMainViewModel = new MainPageModel();
        objMainViewModel.tbl_Notification = lstNotifications;
        objMainViewModel.tbl_User_Notification = lstUserNotifications;

        return View(objMainViewModel);
    }
}

如果是.NET Framework项目,不需要依赖注入的话,可以直接在方法内实例化DbContext:

public ActionResult Index()
{
    using (var context = new NotificationDbContext())
    {
        List<tbl_notification> lstNotifications = context.tbl_notifications.ToList();
        List<tbl_user_notification> lstUserNotifications = context.tbl_user_notifications.ToList();

        MainPageModel objMainViewModel = new MainPageModel();
        objMainViewModel.tbl_Notification = lstNotifications;
        objMainViewModel.tbl_User_Notification = lstUserNotifications;

        return View(objMainViewModel);
    }
}

步骤3:单视图多模型校验配置

你需要先给MainPageModel的两个集合属性,以及集合对应的实体类属性加上数据注解校验规则,示例:

public class tbl_notification
{
    [Required(ErrorMessage = "通知内容不能为空")]
    public string notificationText { get; set; }
    // 其他属性
}

public class tbl_user_notification
{
    [Required(ErrorMessage = "用户名不能为空")]
    public string userName { get; set; }
    // 其他属性
}

public class MainPageModel
{
    public List<tbl_notification> tbl_Notification { get; set; }
    public List<tbl_user_notification> tbl_User_Notification { get; set; }
}

视图中提交表单时,加上校验标签即可触发校验,示例表单片段:

<form asp-action="Submit" method="post">
    @for (int i = 0; i < Model.tbl_Notification.Count; i++)
    {
        <input asp-for="@Model.tbl_Notification[i].notificationText" />
        <span asp-validation-for="@Model.tbl_Notification[i].notificationText" class="text-danger"></span>
    }
    @for (int i = 0; i < Model.tbl_User_Notification.Count; i++)
    {
        <input asp-for="@Model.tbl_User_Notification[i].userName" />
        <span asp-validation-for="@Model.tbl_User_Notification[i].userName" class="text-danger"></span>
    }
    <button type="submit">提交</button>
</form>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

提交数据的后端Action中判断校验结果即可:

[HttpPost]
public ActionResult Submit(MainPageModel model)
{
    if (ModelState.IsValid)
    {
        // 校验通过,执行业务逻辑
        return RedirectToAction("Index");
    }
    // 校验不通过,返回原视图带错误信息
    return View("Index", model);
}

内容的提问来源于stack exchange,提问作者Brandon Mifsud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 15:42:03