2015-09-25 57 views
0

頁面加載時,我的日期控件始終爲空。 這是爲什麼? 數據庫中有該控件的數據。頁面加載時爲什麼我的日期控件爲空?

<div class="form-group"> 
    @Html.LabelFor(model => model.StartDate, new { @class = "control- label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.TextBoxFor(model => model.StartDate, new { type = "Date" }) 
     @Html.ValidationMessageFor(model => model.StartDate) 
    </div> 
</div> 

<div class="form-group"> 
    @Html.LabelFor(model => model.EndDate, new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.TextBoxFor(model => model.EndDate, new { type = "Date" }) 
     @Html.ValidationMessageFor(model => model.EndDate) 
    </div> 
</div> 
+3

您需要添加更多詳細信息 - 控制器代碼和樣本模型數據。 –

+0

您是否在控制器中爲您傳遞給視圖的模型填充StartDate? – Luke

+0

您將輸入指定爲'type =「date」'呈現HTML5日期選擇器(注意它僅在Chrome中受支持),這意味着日期必須採用ISO格式('yyyy-MM-dd')。將'[DisplayFormat]'屬性添加到您的屬性 –

回答

-1

正如@Coulton指出,確保你在渲染頁面之前,你的控制器上實際填充模型的StartDateEndDate性能。此外,如果您在班級中使用[DataType(DataType.Date)]標誌,則可以丟棄TextBoxFor幫手,而使用EditorFor幫助程序。

Controller.cs,ganho.Data是一個[DataType(DataType.Date)]標誌一個DateTime屬性:用於填充數據

例子之前創建或編輯視圖(這似乎是你想在那裏建造的觀點)的屬性

[HttpGet] 
    public ActionResult Edit(int? id) 
    { 
     // Omitted code 
     var result = from ganho in db.Ganhos 
        where ganho.GanhoID == id.Value 
        where ganho.Usuario.Id == user.Id 
        select new GanhoEditViewModel 
        { 
         GanhoID = ganho.GanhoID, 
         Valor = ganho.Valor, 
         Comentario = ganho.Comentario, 
         Data = ganho.Data, 
         Descricao = ganho.Descricao, 
         Tipo = ganho.Tipo 
        }; 
     if (result.Count() < 1) 
     { 
      // 404, no such item exists 
      return HttpNotFound(); 
     } 
     return View(result.Single()); 
    } 

Edit.chtml

<!-- Hidden Code, not relevant to the question --> 
<div class="form-group"> 
    @Html.LabelFor(model => model.Data, htmlAttributes: new { @class = "control-label col-md-2"}) 
    <div class="col-md-10"> 
     @Html.EditorFor(model => model.Data, new { htmlAttributes = new { @class = "form-control", @id = "dataInput"} }) 
     @Html.ValidationMessageFor(model => model.Data, "", new { @class = "text-danger"}) 
    </div> 
</div> 

在你設置了一個創建視圖的情況下,可以初始化像這樣的字段:

Controller.cs,ganho.Data是我的DateTime屬性,用戶將顯示一個佔位符數據。

[HttpGet] 
public ActionResult Create() 
{ 
    var model = new Ganho() 
    { 
     // ... 
     Data = DateTime.Now, // Using the current date and time as a placeholder 
     // ... 
    }; 
    return View(model); 
} 

請注意,在所有示例中,我都使用了Strongy Typed視圖!

相關問題