2011-09-11 47 views
0

我在MVC中有以下自定义视图控件。但是,它根本不起作用。MVC的自定义视图控件不起作用?

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %> 
<%=Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "timePicker" }) %> 

而这正是我使用它,以及如何:

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

这个模型看起来是这样的:

[Bind()] 
[Table("DailyReports", Schema = "Actives")] 
public class DailyReport 
{ 

    [Key()] 
    [Display(AutoGenerateField = false, AutoGenerateFilter = false)] 
    public int ID { get; set; } 

    [DisplayName("Starttidspunkt")] 
    public DateTime? StartTime { get; set; } 

    [DisplayName("Sluttidspunkt")] 
    public DateTime? EndTime { get; set; } 

    [DisplayName("Time-rapporter")] 
    public virtual ICollection<HourlyReport> HourlyReports { get; set; } 

    public DailyReport() 
    { 

    } 
} 

但是,一个简单的文本框只是表明了,在当现实,我期待视图用户控件显示,因为类型是DateTime。

关于如何解决这个问题的任何建议?

+0

要自动将其用作编辑器模板,[您的局部视图是否必须注册或位于已知位置等](http://blogs.msdn.com/b/nunos /archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx)? – bzlm

回答

2

我假设你正确放置你的模板在EditorTemplates文件夹,并且你正确的类型(即DateTime.aspx)

Beause您使用的是可空类型后,将其命名为,您需要手动指定模板名称。

<%: Html.EditorFor(model => model.StartTime, "NullableDateTimeTemplate")%> 

或者,您可以检查模型元数据以确定类型是否可为空。

<% if (ViewData.ModelMetadata.IsNullableValueType) { %> 
    <%= Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), 
     new { @class = "timePicker" }) %> 
<% } else { %> 
    <%= Html.TextBox("", Model.ToShortDateString(), new { @class = "timePicker" }) %> 
<% } %> 
相关问题