Custom view control for MVC doesn't work?

I have the following custom view control in MVC. However, it doesn't work at all.

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

And this is where I use it from, and how:

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

The model looks like this:

[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()
    {

    }
}

However, a simple textfield just shows up, when in reality, I expect the view user control to show up, since the type is DateTime.

Any suggestions on how to solve this?

Upvotes: 0

Views: 296

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

I'm assuming that you're correctly placing your template in the EditorTemplates folder, and that you're naming it after the correct type (ie DateTime.aspx)

Beause you're using a nullable type, you need to specify the template name manually.

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

Or, you can check the model metadata to determine if the type is nullable.

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

Upvotes: 2

Related Questions