MVC4下拉动态SelectList。什么地方出了错?

时间:2014-05-21 20:41:33

标签: asp.net-mvc-4

我是mvc4的新手并尝试动态生成下拉列表。我想创建一个未来10年的清单。我的理解出错了?

模型

using System.Web.Mvc;
using DropDownList.Models;

namespace DropDownList.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ddlist DropList = new ddlist();
            var years = Enumerable.Range(DateTime.Now.Year, 10);
            var select = new SelectList(years.Select(y => new SelectListItem()
            {
                Text = y.ToString(),
                Value = y.ToString()
            }));
            DropList.CountryList = select.ToList(); 
            return View(DropList);
        }

    }
}

----------控制器-----

using System.Text;
using System.Web.Mvc;

namespace DropDownList.Models
{
    public class ddlist
    {
        [Required(ErrorMessage = "Please select a Country")]
        public string CountryCode { get; set; }

        public IEnumerable<SelectListItem> CountryList
        {
            get;
            set;
        }
    }
}

-------------查看-----------------

@model DropDownList.Models.ddlist 
@{
    Layout = null;
}

@Html.DropDownListFor(
model => model.CountryCode, 
Model.CountryList, "select"
)
@Html.ValidationMessageFor(model => model.CountryCode

以下是输出。我期待看到的像2014年,2015年......

  

选择   System.Web.Mvc.SelectListItem   System.Web.Mvc.SelectListItem   System.Web.Mvc.SelectListItem   System.Web.Mvc.SelectListItem   System.Web.Mvc.SelectListItem   System.Web.Mvc.SelectListItem   System.Web.Mvc.SelectListItem   System.Web.Mvc.SelectListItem   System.Web.Mvc.SelectListItem   System.Web.Mvc.SelectListItem

1 个答案:

答案 0 :(得分:0)

更有可能返回SelectList

1)将模型更改为:

public class ddlist
{
    [Required(ErrorMessage = "Please select a Country")]
    public string CountryCode { get; set; }

    public SelectList CountryList
    {
        get;
        set;
    }
}

2)然后将列表作为SelectList返回给模型:

public ActionResult Index()
{
    DropList ddlist = new ddlist();
    var years = Enumerable.Range(DateTime.Now.Year, 10);
    var select = new SelectList(years.Select(y => new SelectListItem()
    {
        Text = y.ToString(),
        Value = y.ToString()
    }));

    DropList.CountryList = select; //Removing the ToList and Using the SelectList

    return View(DropList);
}