2017-04-22 75 views
0

我想在MVC中创建一个下拉列表,显示接下来的30个日期,并将选定的日期传递给构造函数以及其他事件的详细信息。以下是我目前拥有的,但不起作用。我看了dropdownlistfor但不明白的VisualStudio内的如何创建下一个30日期的下拉列表?

智能感知

在我的模型:

  // GET: Events/Create 
    public ActionResult Create() 
    { 
     ViewBag.OrganizationId = new SelectList(db.Organizations, "OrganizationId", "OrganizationName"); 

     ViewBag.Dates = Event.GetLstOfDates(); 

     return View(); 
    } 

,在我创建视图:

 public static List<DateTime> GetLstOfDates() 
    { 

     List<DateTime> dateList = new List<DateTime>(); 
     dateList = Enumerable.Range(0, 30).Select(d => DateTime.Today.AddDays(d)).ToList(); 

     return dateList; 
在我的控制器

@Html.Label("Select Date", htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.DropDownList("Date", (SelectList)ViewBag.Dates, htmlAttributes: new { @class = "form-control" }) 

    </div> 

回答

0

这就是你如何在你的控制器中使用DropDownListFor

public ActionResult Index() 
     {    
      List<int> ListOfAnyThing = new List<int>() { 1,5,7,8,9,2 }; 
      ViewBag.MyList = new SelectList(ListOfAnyThing); 
      return View(); 
     } 

在你看来

@Html.DropDownListFor(m => m.MyProperty, ViewBag.MyList as IEnumerable<SelectListItem>) 

这种方式的价值你会选择在下拉列表将被分配给myProperty的属性,你的模型将要发送回一个控制器的

+0

所以我从来没有学过的主要事情是,你必须把列表放在控制器中的选择列表中?有趣。谢谢您的帮助!我可以限制只显示日期部分吗?你的建议很好,但它也显示了时间,这是我不需要的下降。 – throwaway3834

+0

尝试转换你的日期字符串像这样 MyDate.ToString(“MM/dd/yyyy”); 然后,而不是将DateTime的列表传递给新的SelectList()构造函数传递字符串列表 –