代码之家  ›  专栏  ›  技术社区  ›  touseefbsb

ASP.NET Core MVC自定义注册页

  •  0
  • touseefbsb  · 技术社区  · 7 年前

    我有一个非常基本的任务 ASP.NET核心MVC 申请。所以我有两个模特 订阅 优惠券 它们有一对多的关系,通过使用下面的模型类和脚手架,我能够生成 下拉列表 在优惠券创建页面上选择当前数据库中的任何订阅。我在用 实体框架 我的数据库和脚手架也是。

    模型类

    public class Subscription
    {
        public string FirstName { get; set; }
    
        [Key]
        public int ID { get; set; }
        [Required]
        public string Identifier { get; set; }
        public bool State { get; set; }
        [Required]
        public string Description { get; set; }
        [Required]
        public int MonthlyPrice { get; set; }
        [Required]
        public int MinMonthlyPrice { get; set; }
        [Required]
        public int MonthlyDiscount { get; set; }
        public virtual ICollection<Coupon> Coupons { get; set; }
        public virtual ICollection<RegisterViewModel> Registrations { get; set; }
    }
    
    public class Coupon
    {
        [Required]
        public string CouponCode { get; set; }
        [Required]
        public DateTime StartTime { get; set; }
        [Required]
        public DateTime EndTime { get; set; }
        [Key]
        public int ID { get; set; }
        public int Discount { get; set; }
        public bool IsPercentage { get; set; }
        [ForeignKey("Identifier")]
        public int SubscriptionId { get; set; }
        public virtual Subscription Identifier { get; set; }
        [Required]
        public int ValidMonths { get; set; }
        public bool IsSponsored { get; set; }
        [Required]
        public int Length { get; set; }
        [Required]
        public int Quantity { get; set; }       
    
    }
    

    现在我要我的 登记处 佩奇,我使用的是 个人用户帐户 我只想在优惠券页面上包含相同的下拉列表来选择“订阅”,我想在注册页面上包含相同的下拉列表。我该怎么做? 会计控制员 一点也没有 应用程序上下文 它的构造器参数不同于“couponscontroller”这样的其他控制器,所以这就是为什么我很难在注册页上找到如何从数据库获取数据的方法。

    我知道下面的代码有助于获取订阅列表并从中仅获取特定属性。

     // GET: Coupons/Create
        public IActionResult Create()
        {
            ViewData["SubscriptionId"] = new SelectList(_context.Subscription, "ID", "Identifier");
            return View();
        }
    

    我想在我的注册页面上使用同样的东西,但是在Buffice控制器上不存在DbCub,我不能在BCZ上新建它,我不知道在构造函数中提供什么选项。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Rixium    7 年前

    如果您已经有了dbcontext,那么如果您创建一个类似于其他控制器的构造函数,它应该会自动被注入。

    private ApplicationDbContext _db;
    
    public AccountsController(ApplicationDbContext db)
    {
        _db = db;
    }
    

    然后你可以通过它访问你的数据库。如果不起作用,请检查启动类的configureservices中是否有类似的内容:

    services.AddTransient<ApplicationDbContext>();
    

    如果您的其他控制器有权访问dbcontext,那么应该已经存在类似于该行的内容。