来自数据库的MVC中的dropdownlist

时间:2017-01-23 21:36:11

标签: asp.net-mvc razor

我试图将数据从存储在SQL 2008中的表中提取到我的MVC4

在我的控制器中:

 public ActionResult Test()
    {
       SurveyEntities survey = new SurveyEntities();

       var doctorList = survey.Doctors.ToList();
       return View(doctorList);
    }

并在我的视图中:

@model IEnumerable<Survey.DataAccess.Doctor> 

@{
    ViewBag.Title = "Test";
}

<h2>Test</h2> 

@using (Html.BeginForm("Test", "Home", FormMethod.Post))
{
  @Html.DropDownListFor(m => m.)
}

但是我无法访问m中的字段名称,例如医生的姓名,将其绑定到下拉列表。

我哪里错了?

3 个答案:

答案 0 :(得分:1)

如果您不需要绑定到结果值,您也可以使用
Html.DropDownList('name', new SelectList(Model))

如果您必须使用DropDownList,则必须更改建模并添加一个属性以绑定选择结果,如

Html.DropDownListFor(m=>m.DoctorId, new SelectList(Model.Doctors).....

答案 1 :(得分:1)

通常,您希望使用 ViewModel ,以便在将表单发回服务器时检索所选的 doctorId 。< / p>

例如,

enter image description here

模型

public class SurveyModel
{
    public string SelectedDoctorId { get; set; }
    public IList<SelectListItem> AvailableDoctors { get; set; }

    public SurveyModel()
    {
        AvailableDoctors = new List<SelectListItem>();
    }
}

视图

@model DemoMvc.Models.SurveyModel
@using (Html.BeginForm("Index", "Home"))
{
    @Html.DropDownListFor(m => m.SelectedDoctorId, Model.AvailableDoctors)
    <input type="submit" value="Submit" />

}

控制器

public ActionResult Index()
{
    var model = new SurveyModel
    {
        AvailableDoctors = GetDoctorListItems()
    };
    return View(model);
}

[HttpPost]
public ActionResult Index(SurveyModel model)
{
    if (ModelState.IsValid)
    {
        var doctorId = model.SelectedDoctorId;
        // Do something
        return View("Success");
    }
    // If we got this far, something failed, redisplay form
    // Fill AvailableDoctors again; otherwise, DropDownList will be blank.
    model.AvailableDoctors = GetDoctorListItems();
    return View(model);
}

private IList<SelectListItem> GetDoctorListItems()
{
    /*
    SurveyEntities survey = new SurveyEntities();
    return survey.Doctors
        .Select(d => new SelectListItem {Text = d, Value = d.ToString()})
        .ToList();
    */

    // Simulate doctors return from database.
    return new List<SelectListItem>
    {
        new SelectListItem {Text = "John Doe", Value = "1"},
        new SelectListItem {Text = "Eric Newton", Value = "2"}
    };
}

答案 2 :(得分:1)

您可以将此代码放在Test方法中:

> ViewData["doctors"] = new SelectList(doctorList,"value", "text");

然后在视图中:

     @using (Html.BeginForm("Test", "Home", FormMethod.Post)) 
{
     @Html.DropDownList("name", ViewData["doctors"] as SelectList) 
     input type="submit" value="Submit" />

}