C# 在ASP.NET MVC中从数据库填充下拉菜单

C# 在ASP.NET MVC中从数据库填充下拉菜单,c#,asp.net-mvc,C#,Asp.net Mvc,在3个不同的下拉菜单(患者、医生、诊所)中选择一些选项后,我可以创建一个“预约” 我需要有关创建和填充这3个下拉菜单的帮助 我是ASP.NETMVC和C的新手。非常感谢您的帮助 我将包括约会控制器和约会创建视图代码 委任控制员 约会“创建”视图 在CreateControllerGet中,应创建3个viewbag,如 ViewBag.Patient = Database.Patient.ToList(); ... 在视图中,使用dropdownlist: @Html.DropDownList

在3个不同的下拉菜单(患者、医生、诊所)中选择一些选项后,我可以创建一个“预约”

我需要有关创建和填充这3个下拉菜单的帮助

我是ASP.NETMVC和C的新手。非常感谢您的帮助

我将包括约会控制器和约会创建视图代码

委任控制员

约会“创建”视图


在CreateControllerGet中,应创建3个viewbag,如

ViewBag.Patient = Database.Patient.ToList();

...
在视图中,使用dropdownlist:

@Html.DropDownList("PatientId",  new SelectList(ViewBag.Accounts, "PatientId", "PatientName")), "choose the patient", new { @class = "form-control" }))

如果下拉菜单选项位于数据库中,为什么不向模型中添加一个列表,在GET ActionMethod中填充该列表,然后使用DropdownListFor helper标记呈现它呢。 例如

public class Appointment
{
   public IEnumerable<SelectListItem> Clinic {get; set;}
 //You should add this for every dropdown menu you intend to put in the list.
 //I am guessing you already have a model like this as this was not in the question
}

public class Clinic
{
  public int ClinicId {get; set;}
  public string ClinicName {get; set;}
}
像以前一样,您必须对所有字段执行此操作。如果您担心需要多次往返数据库以获取值,请对Z.EntityFrameWork nuget包进行一些研究,该包允许您运行批处理SQL语句,以便在一次数据库往返中获得所有三个结果

然后在视图中,您可以这样做

@Html.DropDownListFor(m => m.ClinicId, Model.Clinic, "Select Clinic", new { @class = "form-control", id = "clinic" })

我不确定我是否理解,但代码通常会在布局中。我建议您首先只使用html构建菜单。这样就更容易找到用代码构建它的方法了。问题到底出在哪里?我不清楚您试图填充下拉列表的位置。我在当前视图中添加了一个屏幕截图,而不是常规输入,我想要从数据库中填充真实医生、患者和诊所的下拉菜单。
public class Appointment
{
   public IEnumerable<SelectListItem> Clinic {get; set;}
 //You should add this for every dropdown menu you intend to put in the list.
 //I am guessing you already have a model like this as this was not in the question
}

public class Clinic
{
  public int ClinicId {get; set;}
  public string ClinicName {get; set;}
}
    public ActionResult Create()
    {
        var Clinic = context.Clinic.ToList();
        var model = new Appointments()
        {
           Clinic = Clinic.Select(x => new SelectListItem
           {
             Value = x.ClinicId.ToString(),
             Text = x.ClinicName
           }
        }
        return View(model);
    }
@Html.DropDownListFor(m => m.ClinicId, Model.Clinic, "Select Clinic", new { @class = "form-control", id = "clinic" })