0

I am using mvc3 and razor is my view engine how i get date picker with out using scripts in my
view.

6 Answers 6

7

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>
2
  • 1
    I had multiple dates in my form so instead of "#datepicker" I used ".datepicker". Then in the HTML changed 'id = "datepicker"' to '@class = "datepicker"'.
    – Matt
    Commented Oct 27, 2015 at 0:46
  • I put this code in my form, just got me a text box. Commented Jan 13, 2020 at 21:12
4

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

3

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.

1
  • Thanks plurby, works perfectly, I just had to update the css and jQuery links to the latest versions, maybe an MVC4 thing???
    – Bojangles
    Commented Oct 14, 2013 at 0:55
1

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.

0
@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>
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.