2012-09-14 68 views
0

enter image description here如何在編輯視圖中初始化日期選擇器?

我有一個模型,如下所示:

using System; 
using System.ComponentModel.DataAnnotations; 
using System.Data.Entity; 

namespace MvcMovie.Models 
{ 
    public class Movie 
    { 
     public int ID { get; set; } 

     [Required] 
     public string Title { get; set; } 

     [DataType(DataType.Date)] 
     public DateTime ReleaseDate { get; set; } 

     [Required] 
     public string Genre { get; set; } 

     [Range(1, 100)] 
     public decimal Price { get; set; } 

     [StringLength(5)] 
     public string Rating { get; set; } 
    } 

    public class MovieDbContext : DbContext 
    { 
     public DbSet<Movie> Movies { get; set; } 
    } 
} 

日期選擇器是默認啓用的,但是當編輯觀點看來,日期字段不會自動反映前值。如何在編輯視圖出現時初始化日期選擇器?

@model MvcMovie.Models.Movie 

@{ 
    ViewBag.Title = "Edit"; 
} 

<h2>Edit</h2> 

@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>Movie</legend> 

     @Html.HiddenFor(model => model.ID) 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Title) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Title) 
      @Html.ValidationMessageFor(model => model.Title) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.ReleaseDate) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.ReleaseDate) 
      @Html.ValidationMessageFor(model => model.ReleaseDate) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Genre) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Genre) 
      @Html.ValidationMessageFor(model => model.Genre) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Price) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Price) 
      @Html.ValidationMessageFor(model => model.Price) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Rating) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Rating) 
      @Html.ValidationMessageFor(model => model.Rating) 
     </div> 

     <p> 
      <input type="submit" value="Save" /> 
     </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 
+0

請顯示視圖語法。如實施例看[在模型設置初始值DataType.DateTime] [1] [1]:http://stackoverflow.com/questions/4790096/setting-initial-value-for-datatype- datetime-in-model – webdeveloper

回答

0

在共享命名的EditorTemplates中創建一個文件夾,並放置一個文件名稱DateTime.cshtml。 然後,您將以下代碼添加到該文件。

@model DateTime 
@Html.TextBox("", String.Format("{0:d}", Model.Date.ToShortDateString())) 
+0

它不起作用。 –

+0

添加了文件夾EditorTemplates,比如Views/Shared/EditorTemplates?該文件夾中的文件? – Rikard

+0

你試過了嗎?這是行不通的。 –

相關問題