2012-09-14 67 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

你试过了吗?这是行不通的。 –

相关问题