asp.net核心mvc自定义注册页面

时间:2018-07-14 09:43:14

标签: c# asp.net asp.net-mvc entity-framework-core

我的 ASP.NET CORE MVC 应用程序中有一项非常基本的任务。所以问题是,我有2个模型 Subscriptions Coupons ,它们之间存在一对多的关系,通过使用以下模型类和脚手架,我能够生成一个 dropDownList优惠券创建页面上的可以选择数据库中当前存在的任何订阅。我也在数据库和脚手架上使用实体框架

模型类

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; }       

}

现在我要在我的注册页上添加相同的下拉菜单,我正在使用个人用户帐户的内置注册系统,我只想添加相同的下拉菜单我在优惠券页面上选择“订阅”,我希望在注册页面上选择相同的主题。我怎样才能做到这一点? AccountsController 在其构造函数参数中未获得任何 ApplicationDbContext ,这与其他控制器(例如“ couponsController”)不同,因此这就是为什么我无法确定如何从注册页面上的数据库中获取数据的原因

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

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

我想在我的注册页面上找到同样的东西,但是acconsoleController中不存在dbcontext,我无法对其进行更新,因为我不知道在构造函数中要提供什么选项。

1 个答案:

答案 0 :(得分:1)

如果您已经拥有DbContext,则在创建与其他控制器类似的构造函数时,应该自动将其注入。

private ApplicationDbContext _db;

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

然后,您可以通过它访问您的DbSet。如果这不起作用,请检查Startup类中的ConfigureServices中是否有类似内容:

services.AddTransient<ApplicationDbContext>();

如果您的其他控制器可以访问DbContext,则应该已经有与该行相似的内容。

相关问题