显示并获取DropDownList中列出的值

本文关键字:获取 DropDownList 显示 | 更新日期: 2023-09-27 18:00:06

我的控制器类;

在以下示例中,returnAllHuman();将返回List<SelectListItem>

public ActionResult Index()
    {
        var list = returnAllHuman(); // List<SelectListItem>
        ViewData["all_Human"] = list;
        return View();
    }

在视图中

 @Html.DropDownList("all_Human")

1.)数值不会显示

2.)我需要获取所选的值并将其显示在文本字段中。我该怎么做?

更新:我从下面的代码中删除了异常处理部分

  public List<SelectListItem> returnAllHuman()
    {
        var i = new List<SelectListItem>();

            using (SqlCommand com = new SqlCommand("SELECT * FROM Names", con))
            {
                con.Open();
                SqlDataReader s = com.ExecuteReader();

                while (s.Read())
                {
                    i.Add(new SelectListItem
                    {
                        Value = s.GetString(0), 
                        Text = s.GetString(1)  
                    });
                }
                           con.Close();

        return i;
    }

显示并获取DropDownList中列出的值

首先定义一个视图模型:

public class MyViewModel
{
    [Required]
    public string SelectedHuman { get; set; }
    public IEnumerable<SelectListItem> AllHumans { get; set; }
}

然后让你的控制器填充这个模型并传递到视图:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        model.AllHumans = returnAllHuman(); // List<SelectListItem>
        return View(model);
    }
    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // there was a validation error => for example the user didn't make
            // any selection => rebind the AllHumans property and redisplay the view
            model.AllHumans = returnAllHuman();
            return View(model);
        }
        // at this stage we know that the model is valid and model.SelectedHuman
        // will contain the selected value
        // => we could do some processing here with it
        return Content(string.Format("Thanks for selecting: {0}", model.SelectedHuman));
    }
}

然后在你的强类型视图中:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.SelectedHuman, Model.AllHumans, "-- Select --")
    @Html.ValidationFor(x => x.SelectedHuman)
    <button type="submit">OK</button>
}