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.
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
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()) %>
精彩评论