2017-04-22 74 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()構造函數傳遞字符串列表 –