I am trying to implement a jquery datepicker in my MVC 3 application. It works fine in edit mode, but when trying to use it in the create view, I get the null dictionary exception which tells me it cannot take a null value and needs a value of DateTime. Of course it's going to be null, your trying to create a new field. How can I get this to work.
2 Answers
I would use EditorTemplate instead of custom helper
Create new partial view Date.ascx and place it in \Views\Shared\EditorTemplates\
<%@ Control Language="C#" %>
<%: Html.TextBox("", Model == null ? "" : ((DateTime)Model).ToString("yyyy-MM-dd"), new { @class = "datepicker", @readonly = "readonly" })%>
That works fine for all properties of type DateTime
2 Comments
#HireDate, #EnrollmentDate on every page, so placing this script in _Layout.cshtml is not the best solution. Moreover, you have to remember that every time you add new view with date fields you have to modify this script.A lot easier using custom helper, im using helper below in one of my application.
1.Create Helper class
namespace System.Web.Mvc.Html
{
public static class DatePickerHelper
{
public static string DatePicker(this HtmlHelper htmlHelper, string id, string name, string value)
{
StringBuilder sBuilder = new StringBuilder();
sBuilder.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");
sBuilder.AppendLine("$(function () {");
sBuilder.AppendLine("$(\"#" + id + "\").datepicker({");
sBuilder.AppendLine("showOn: \"button\",");
sBuilder.AppendLine("buttonImage: \"/Content/images/icon-calendar.gif\",");
sBuilder.AppendLine("dateFormat: 'dd/mm/yy',");
sBuilder.AppendLine("buttonImageOnly: true");
sBuilder.AppendLine(" });");
sBuilder.AppendLine("});");
sBuilder.AppendLine("</script>");
sBuilder.AppendLine("<input type=\"text\" value=\"" + value + "\" id=\"" + id + "\" name=\""+name+"\" class=\"SmallTextBox\" />");
return sBuilder.ToString();
}
}
}
use it like this on your view (For creating) in my case i have Controller call Employee, make sure you use this pattern if you are using data model { "YouControllerName.PropertyName" and "YouControllerName_PropertyName"
<%= Html.DatePicker("Employee_StartDate","Employee.StartDate","") %>
For editing
<%=Html.DatePicker("Employee_StartDate","Employee.StartDate",Model.Employee.StartDate.ToShortDateString()) %>