2015-03-02 22 views
-2

我正在使用實體框架2013和Razors。如何在實體框架中添加日期和下拉列表

我想把日期元素和下拉列表放在我的.cshtml的ASP.NET MVC5視圖中。

這是我的代碼

@Html.LabelFor(model => model.AllocationDate, htmlAttributes: new { @class = "control-label col-md-2" }) 

@Html.EditorFor(model => model.AllocationDate, new { htmlAttributes = new { @class = "form-control" } }) 
@Html.ValidationMessageFor(model => model.AllocationDate, "", new { @class = "text-danger" }) 


@Html.LabelFor(model => model.PortORterminal, htmlAttributes: new { @class = "control-label col-md-2" }) 

@Html.EditorFor(model => model.PortORterminal, new { htmlAttributes = new { @class = "form-control" } }) 
@Html.ValidationMessageFor(model => model.PortORterminal, "", new { @class = "text-danger" }) 


@Html.LabelFor(model => model.CurrentDestination, htmlAttributes: new { @class = "control-label col-md-2" }) 

@Html.EditorFor(model => model.CurrentDestination, new { htmlAttributes = new { @class = "form-control" } }) 
@Html.ValidationMessageFor(model => model.CurrentDestination, "", new { @class = "text-danger" }) 
+1

可能的[使用Razor的MVC 4中的DropDownList]的副本(http://stackoverflow.com/questions/17727386/dropdownlist-in-mvc-4-with-razor) – 2015-03-02 20:09:59

+1

http://stackoverflow.com/questions/ 17727386/dropdownlist-in-mvc-4-with-razor – 2015-03-02 20:10:13

+0

嗨米迦勒,這是偉大的工作很好 – 2015-03-05 19:02:34

回答

0

定義自定義視圖模型

public class FilterViewModel 
    { 
     public int SelectedIdPeriodo { get; set; } 
     public IEnumerable<SelectListItem> Periodos { get; set; } 
    } 

在您的控制器設置的項目列表中,選擇的項目

var model = new FilterViewModel 
         { 
          //set the selected Id 
          SelectedIdPeriodo = currentPeriod, 
          //set the items list 
          Periodos = db.Periodoes.ToList().Select(x => new SelectListItem 
                      { 
                       Value = x.IdPeriodo.ToStringInvariant(), 
                       Text = x.PeriodoCod 
                      }) 
         }; 

在您查看:

@model App.Models.ViewModels.FilterViewModel 


@using (Html.BeginForm()) 
{ 
    <div>  
     @Html.Label("Periodo: ") 

     @Html.DropDownListFor(
      x => x.SelectedIdPeriodo, 
      Model.Periodos, 
      new { onchange = "form.submit();" } 
     ) 
     @Html.AntiForgeryToken() 
    </div> 
} 
相關問題