【发布时间】:2019-03-31 21:40:38
【问题描述】:
在 Create 视图中,管理员可以创建一个新菜并从下拉列表中选择其类型(DishTypes 来自数据库)。问题是我不知道如何在Create 视图中设计DishesViewModel、DishesController 和下拉列表。
这是Dishes模型
public class Dishes
{
[Key]
[Required]
public int DishID { get; set; }
[Required]
public string Dishname { get; set; }
public int DishTypeID { get; set; }
[ForeignKey("DishTypeID")]
public virtual DishTypes DishTypes { get; set; }
}
这里是 DishTypes 模型
public class DishTypes
{
[Required]
public int DishTypeID { get; set; }
[Required]
public string DishTypeName { get; set; }
}
这是我目前的 Dishes 视图模型(我使用 Automapoper 将它们映射到域模型)
public class DishesVM
{
[Required]
public string DishName{ get; set; }
[Required]
public int DishTypeID{ get; set; }
[Required]
public string DishTypeName { get; set; }
}
这是 DishesController
public class DishesController: Controller
{
[HttpGet]
public async Task<IActionResult> Create()
{
// it should pass a list of dishTypes to my view so when admins create a dish they can choose dishtype from a dropdown list
//I down't want to use ViewBag or ViewData
return View()
}
}
这是创建视图
@model DataLayers.Models.ViewModels.DishesVM
<form asp-controller="Dishes" asp-action="Create">
<label class="label" asp-for="Dishname"></label>
<input class="input" type="text" asp-for="Dishname">
//a drop down list, which enables admins choose dishtypes, is needed here
</form
最后是 DishRepository
public class DishRepository
{
public async Task<IEnumerable<Dishes>> GetAllDishesAsync()
{
return await _RepositoryContext.Set<Dishes>().ToListAsync();
}
}
随意改变一切。
【问题讨论】:
-
您发布了很多代码,几乎没有一个与您想要的相关。您似乎也没有尝试过任何东西
-
@CamiloTerevinto 哪一部分是不必要的?我尝试了很多方法,但都没有奏效,所以我没有在这里添加它们以保持清晰
-
好吧,你错过了很多东西。 1)下拉列表(应该是最简单和最快的),2)从数据库中获取 DishTypes,3)从控制器中使用它,最后,4)将该数据传递给视图。没有任何工作吗?
-
@CamiloTerevinto 1) 下拉列表的 HTML 很简单,但如何检索其数据? 2)我可以从数据库中获取菜品类型,但是当我将菜品VM 传递给查看时,因为其他 fild(DishName) 为 NULL,所以表单验证会发出警告并说需要菜名。正如我所提到的,我是新手。
-
ProductTypeID和ProductTypeName的用途是什么?
标签: c# asp.net-core entity-framework-core