I am using mvc3 and razor is my view engine how i get date picker with out using scripts in my
view.
6 Answers
You can create a script in the directory scripts of your project.
Basic example:
$(document).ready(function () { $("#datepicker").datepicker({ });});
in your view:
@model YourProjectName.Models.User
....
<div class="editor-field">
@Html.TextBoxFor(model => model.Dateadd, new { @Value = DateTime.Now, id = "datepicker" })
@Html.ValidationMessageFor(model => model.Dateadd)
</div>
-
1I had multiple dates in my form so instead of "#datepicker" I used ".datepicker". Then in the HTML changed 'id = "datepicker"' to '@class = "datepicker"'.– MattCommented Oct 27, 2015 at 0:46
-
I think you are going to have to use a script, check out jqueryui datepicker. Its a nice easy to use library and supports theming
I answered here, check it out: http://forums.asp.net/post/4647234.aspx
Basically you're using a template with a script in one location and calling it with EditorFor.
-
Thanks plurby, works perfectly, I just had to update the css and jQuery links to the latest versions, maybe an MVC4 thing??? Commented Oct 14, 2013 at 0:55
To advisers here: it's a bad practice to use scripts inside partial views (templates).
In my case it does not work at all. Because accessing jquery happens before it's included as js file. Plus you cannot predict where exactly you would put this datepicker control. Also, you will have this "ready" block for every editor on the page.
RenderSection would bring some order to all this, but it does not work for partialviews and templates.
So just move javascript code from a template (partialview) to a view.
@model Nullable<System.DateTime>
@if ( Model.HasValue ) {
@Html.TextBox( "" , String.Format( "{0:yyyy-MM-dd HH:mm}" , Model.Value ) , new {
@class = "textbox" , @style = "width:400px;" } )
}
else {
@Html.TextBox( "" , String.Format( "{0:yyyy-MM-dd HH:mm}" , DateTime.Now ) , new {
@class = "textbox" , @style = "width:400px;" } )
}
@{
string name = ViewData.TemplateInfo.HtmlFieldPrefix;
string id = name.Replace( ".", "_" );
}
<script type="text/javascript">
$(document).ready(function () {
$("#@id").datepicker
({
dateFormat: 'dd/mm/yy',
showStatus: true,
showWeeks: true,
highlightWeek: true,
numberOfMonths: 1,
showAnim: "scale",
showOptions: {
origin: ["top", "left"]
}
});
});
</script>
If you use an Editor Template for the DateTime type, you can use an HTML5 date picker (i.e. <input type="date" />
). Essentially you put a view called DateTime.cshtml in a folder called Views/Shared/EditorTemplates, then you can style the editor however you like. One example is in an answer here.