Asp.Net MVC中使用DropDownListFor

在Asp.Net MVC中可以用DropDownListFor的方式来让用户选择已定列表中的一个数值。用法不复杂,这里简单做一个记录。

首先我们要定义一个 Model,用户在 DropDownList 中选择指定的值赋给属性ReadyTimeHour

public class EricSunModel
{
    public string ReadyTimeHour { get; set; }
}

Model定义完毕之后,接下来处理Controller的逻辑

【注:这里用了ViewData来记录DropDownList中所要显示的所有列表数值】

public ActionResult EricSunAction()
{
    EricSunModel esModel = new EricSunModel();
    esModel.ReadyTimeHour = "00";
    
    GenerateReadyTimeViewData();
    
    return View(esModel);
}
    
private void GenerateReadyTimeViewData()
{
    ViewData["HourList"] = GetTimeHourList();
}
    
private List<SelectListItem> GetTimeHourList()
{
    List<SelectListItem> hourList = new List<SelectListItem>();
    
    for (int i = 0; i < 24; i++)
    {
        if (i < 10)
        {
            hourList.Add(new SelectListItem { Text = "0" + i.ToString(), Value = "0" + i.ToString() });
        }
        else
        {
            hourList.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
        }
    }
    
    return hourList;
}

接下来我们在View中可以用下面一行代码来绑定DropDownList

【注:第一个参数为绑定Model中的属性,即-->要为此属性赋值】

【注:第二个参数为DropDownList的所有数据源】

@Html.DropDownListFor(m => m.ReadyTimeHour, ViewData["HourList"] as List<SelectListItem>)

截图如下所示

查看本栏目更多精彩内容:http://www.bianceng.cn/webkf/aspx/




转载请注明:http://www.shhjfk.com/bcxx/bcxx/34.html

  • 上一篇文章: 没有了
  •   
  • 下一篇文章: