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



我的ASP.NET CORE 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; }       
}

现在我想在我的注册页面上使用相同的下拉菜单,我正在使用个人用户账户的内置注册系统,我只想在优惠券页面上包括相同的下拉列表来选择";订阅";我想要注册页面上的同一个。我该怎么做AccountsController在其构造函数参数中没有获得任何ApplicationDbContext;couponsController";所以这就是为什么我很难弄清楚如何从注册页面上的数据库中获取数据。

我知道下面的代码可以帮助我获得订阅列表,并且只从中获得特定的属性

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

我希望在我的注册页面上有同样的东西,但AccountsController上不存在dbcontext,我无法更新它,因为我不知道在构造函数中提供什么选项。

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

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

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

services.AddTransient<ApplicationDbContext>();

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

最新更新