How to use datetime picker as editortemplate - asp.net-mvc

How can i use datetime picker in my mvc view .
EditorTemplate : Datetime.cshtml
#model DateTime?
#Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy"):"", new { #class = "datefield" })
Model :
[Required]
public DateTime DateOfBirth { get; set; }.
Also jquery.ui.all.css is under my solution content>themes>base
Here is the partial view where the datepicker is needed .
#model PersonalDetails`
`
#Html.LabelFor(model => model.DateOfBirth)
#Html.EditorFor(model => model.DateOfBirth, new { #placeholder = "Date Of Birth", #class = "datefield" ,#type="text" })
#Html.ValidationMessageFor(model => model.DateOfBirth)
Here the date field is coming in the format specified in the Datetime editor template. But the calendor image is not coming.

Assume you have editor set up for jQuery datepicker:
#Html.EditorFor(model => model.DateOfBirth, new { #placeholder = "Date Of Birth", #class = "datefield", #type="text" })
Check if your JS code has working properly by browser debugging, your datepicker code should looks like this:
<script type="text/javascript">
$(document).ready(function () {
$(".datefield").datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
showOtherMonths: true,
selectOtherMonths: true,
// other datepicker settings here as you want
});
});
</script>
Then make sure jQuery UI CSS file has included either inside Layout.cshtml or inside head tag on your page, at this step your calendar image should be shown besides date editor:
<link rel="stylesheet" href="~/Content/themes/base/jquery.ui.all.css" type="text/css">
<script src="~/Scripts/jQuery-[version].js" type="text/javascript">
<script src="~/Scripts/jQuery-ui-[version].js" type="text/javascript">
To simplify those script and style declarations, I suggest you learning MVC styles/scripts bundling.
Any suggestions welcome.

Related

getting null value in textboxfor tool for date in mvc

I am adding bootstrap date in textboxfor tool and its showing also.
But, the problem is that I am getting null value in controller.
Here is my code
View
#using (Html.BeginForm("Create", "StaffRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(model => model.JoinDate, new { #class = "form-control", placeholder = "DD/MM/YYYY", Name = "date" })
}
Script File
$(document).ready(function () {
var date_input = $('input[name="date"]'); //our date input has the name "date"
var container = $('.bootstrap-iso form').length > 0 ? $('.bootstrap-iso form').parent() : "body";
date_input.datepicker({
format: 'dd/mm/yyyy',
container: container,
todayHighlight: true,
autoclose: true,
})
})
Controller
public ActionResult Create(StaffRegistrationViewModel staffRegistrationViewModel)
{
//here is my code
}
Now, when I click the button at that time at controller side null value is coming.[I saw by doing in debug mode]
In staffRegistrationViewModel, JoinDate field showing null value.
Thank You.
Generally Bootstrap DateTime Picker will Implement like this...
and in this way even you will get the value of selected datetime in post action method(in controller)...
// View Code
<div id="datefrom" class="input-group date">
#Html.TextBoxFor(model => model.FromDate, new { #class = "form-control", #readonly = "readonly", style = "position: static;" })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
// Jquery Code
$('#datefrom').datetimepicker({
format: 'DD/MM/YYYY HH:mm:ss',
ignoreReadonly: true,
useCurrent: false});

datepicker is not a function- attempting to load a datepicker on an MVC form field

I am getting the error "$(...).datepicker() is not a function as I try to set a bootstrap datepicker on a form field in my MVC/razor form. I've read similar posts and can't seem to get their solutions to work. It seems like the order of dependencies matters. Any advice would be appreciated. I've referenced this as one solution I've tried without success. How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?
Script Block
<script src="~/Scripts/jquery-3.1.1.js"></script>
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/moment.js"></script>
<script src="~/Scripts/bootstrap-datepicker.js"></script>
<link href="~/Content/bootstrap-datepicker.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet"/>
<script type="text/javascript">
$(function () {
$('.datepicker').datepicker();
});
</script>
Form Field
<div class="form-group">
#Html.LabelFor(model => model.TrainingDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TrainingDate, new { htmlAttributes = new { #class = "form-control datepicker" } })
#Html.ValidationMessageFor(model => model.TrainingDate, "", new { #class = "text-danger" })
</div>
</div>
There must be some conflict on your jquery. Also you have to remove jquery library so remove this one <script src="~/Scripts/jquery-3.1.1.js"></script> .
for no conflict on jquery, you can do your code like this
<script type="text/javascript">
$.noConflict();
$(function () {
$('.datepicker').datepicker();
});
</script>

How add Mask to InputTags in asp.net mvc5

I have input-tag in my view, but I want set mask for each tag : digit-digit
like: 1-3, 44-56
How can I set that?
you can do it like this
first all two libraries in head
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.js"></script>
then below will be your textbox
#Html.TextBoxFor(x => x.Number, new { #class = "form-control", #id = "phone" } )
here x.Number will be the property
and your script will be
<script type="text/javascript">
$(function () {
$("#phone").mask("99-99");
});
</script>

DatePicker Editor Template

Below is an EditorTemplate that renders a Bootstrap datetimepicker with EditorFor helpers, the problem I am seeing is with the script section. It works OK for one DateTimePicker per view - but since I am using class selector, whenever I use 2 or more DateTimePickers per view it renders duplicate <script> sections, confusing the DOM as to on which TextBox to invoke the calendar. What am I missing here?
#model DateTime?
<div class='input-group date datePicker'>
<span class="input-group-sm">
#Html.TextBox("", Model.HasValue ? Model.Value.ToString("d") : String.Empty)
</span>
</div>
<script type="text/javascript">
$(function() {
$('.datePicker').datetimepicker({
pickTime: false
});
});
</script>
The problem you have as you have correctly deduced is that the script block defined in the editor template will run twice when you have two datepickers included in a view; When it is run twice, the plugin's behaviour is not as expected.
One solution to this would be to target only the datepicker input in the editor template in each script block. For example,
#model DateTime?
<div class='input-group date datePicker'>
<span class="input-group-sm">
#Html.TextBox("", Model.HasValue ? Model.Value.ToString("d") : String.Empty)
</span>
</div>
<script type="text/javascript">
$(function() {
// target only the input in this editor template
$('##Html.IdForModel()').datetimepicker({
pickTime: false
});
});
</script>
As far as rendering the script once, what about the following? It works for me so far. Any potential issues?
Editor Template - DateTime.cshtml
#model System.DateTime?
#Html.TextBox("", String.Format("{0:d}", Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { #class = "datepicker" })
_Layout.cshtml
<script type="text/javascript">
$().ready(function () {
$('.datepicker').datepicker({
changeMonth: true,
changeYear: true,
showOn: "button",
buttonImage: "/Images/calendar.gif",
buttonImageOnly: true
});
}
</script>

Date picker in mvc3 with razor view engine

I am using mvc3 and razor is my view engine how i get date picker with out using scripts in my
view.
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>
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.
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.

Resources