1

我的控制器类;

在以下示例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;
    }
4

1 回答 1

3

首先定义一个视图模型:

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>
}
于 2013-02-18T23:04:54.173 回答