How to use TimePicker to DatePicker MVC3 C# - c#

I'm struggling to understand how to combine the TimePicker http://trentrichardson.com/examples/timepicker/ solution to my existing ASP.Net MVC3 C# site that uses DatePicker. DatePicker is currently working fine on it's own, but I need to add the time as well as the date, and TimePicker looks perfect for what I need, only I'm not sure how to implement it.
I see the example gives this code:
$('#example1').datetimepicker();
but I am unsure how to work it into my existing site / DatePicker function.
I have made sure I include these JS files in the HEAD section on the _Layout page, as well as adding the CSS to my existing DatePicker CSS file (jquery-ui-1.7.3.custom.css):
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.7.3.custom.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-timepicker-addon.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-sliderAccess.js")" type="text/javascript"></script>
and on my View page I have this code which displays the input and calls the DatePicker function (this works fine in its current form):
#model test.Models.News
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.News_Date)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.News_Date, "News_Date", new { #ID = "News_Date" })
</div>
<p>
<input type="submit" value="Create" />
</p>
}
<script type="text/javascript">
$(document).ready(function () {
$("#News_Date").datepicker({
showOptions: { speed: 'fast' },
changeMonth: false,
changeYear: false,
dateFormat: 'dd/mm/yy',
gotoCurrent: true
});
});
</script>
I am unsure how to install the TimePicker function so it works with DatePicker on my MVC3 site.
I'd appreciate an explanation if someone wouldn't mind?
Many thanks.

You simply replace your datepicker call with datetimepicker in the view and provide the necessary arguments for both:
<script type="text/javascript">
$(document).ready(function () {
$('#News_Date').datetimepicker({
// Arguments for the date picker
showOptions: { speed: 'fast' },
changeMonth: false,
changeYear: false,
dateFormat: 'dd/mm/yy',
gotoCurrent: true,
// Arguments for the time picker
showSecond: true,
timeFormat: 'hh:mm:ss',
stepHour: 2,
stepMinute: 10,
stepSecond: 10
});
});
</script>

Related

ASP.NET MVC and jQuery DateTimePicker : can't display it

I'm using ASP.NET MVC and in one of my views, I have to implement two DateTime fields which could be filled with a DateTimePicker. Here are my fields :
#Html.EditorFor(s => s.StartApp, new { #id = "Start_App" })
And the second one :
#Html.EditorFor(s => s.EndApp, new { #id = "End_App" })
As you can see, I gave them an id to say that I want these fields as DateTimePicker. Here is what I'm doing in my script :
<script type="text/javascript">
$(document).ready(function () {
$('#Start_App').datetimepicker({
// Arguments for the date picker
showOptions: { speed: 'fast' },
changeMonth: false,
changeYear: false,
dateFormat: 'dd/mm/yy',
gotoCurrent: true,
// Arguments for the time picker
showSecond: true,
timeFormat: 'hh:mm:ss',
stepHour: 2,
stepMinute: 10,
stepSecond: 10
});
$('#End_App').datetimepicker({
// Arguments for the date picker
showOptions: { speed: 'fast' },
changeMonth: false,
changeYear: false,
dateFormat: 'dd/mm/yy',
gotoCurrent: true,
// Arguments for the time picker
showSecond: true,
timeFormat: 'hh:mm:ss',
stepHour: 2,
stepMinute: 10,
stepSecond: 10
});
});
</script>
The problem is that I only have a DatePicker and not a DateTimePicker and I clearly can't understand why. Here are the scripts I'm including :
<script src="#Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.10.4.custom.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.10.4.custom.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.core.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.ui.datepicker.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/DatePickerReady.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.globalize.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.globalize.min.js")" type="text/javascript"></script>
Any idea guys?
DateTimePicker is not a standard JQueryUI functionallity
you will have to use a plugin like http://plugins.jquery.com/datetimepicker/

DatePicker not displaying properly in Bootstrap ASP.NET MVC 5

I have a date picker in my form and it is not displaying properly in any browser
<div class="col-md-10">
#Html.TextBoxFor(model => model.DateJoined, new { #class = "datepicker" })
#Html.ValidationMessageFor(model => model.DateJoined)
</div>
I have added jquery UI and added Javascript like this:
<script src="~/Scripts/jquery-2.1.1.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script type="text/javascript">
$(function () { // will trigger when the document is ready
$('.datepicker').datepicker(); //Initialise any date pickers
});
</script>
And this is how it is displaying in UI:
Demo
JQuery UI
You need to include following files
//css file jQuery UI
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
//jQuery file js reference.
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
//jQuery UI js reference.
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
In the App_Start/Bundle.config
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.min.css",
"~/Content/site.css",
"~/Content/jquery-ui.css"));

Jquery template anchor tag click

SO i have this jquery template and i need to call a jquery or javascript function on the click of this anchor tag. Ive tried it a few different ways.
<a href="yourfunction()"
Ive tried
$('#number').click(function(e){
So if anyone could help it would be highly appreciated. The anchor tag in question is the phone number one with the id of number.
#model OpenRoad.Web.Areas.Marketing.Models.MobyNumberSelectionModel
#{
ViewBag.Title = "Moby Number Selection";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section scripts {
<script type ="text/javascript">
$('#number').click(function (e) {
alert('test');
});
});
mixpanel.track("View Marketing | Moby | Number Selection");
//$(document).on("click", "#number", function (e) {
// event.preventDefault();
// alert('test'); });
//$('#number').click(function (e) {
// Alert('test');
//});
</script>
}
<label class="lgform" style="text-align: left; padding: 10px 0;">Select state and area code:</label>
#Html.DropDownListFor(m => m.State, OpenRoad.Web.Helpers.DropDownLists.GetOptionValues("States", Model.State),
new { #class = "ddtrigger", data_url = "/Marketing/Moby/GetAreaCodes", data_template = "areaCodeTemplate", data_target = "AreaCode" })
#Html.DropDownListFor(m => m.AreaCode, (IEnumerable<SelectListItem>)ViewData["AreaCodes"],
new { #class = "ddtrigger", data_url = "/Marketing/Moby/GetPhoneNumbers",
data_template = "phoneNumberTemplate",
data_target = "phoneNumbers",
data_listtarget="true" })
#Html.HiddenFor(m => m.MobyNumber)
<script id="areaCodeTemplate" type="text/x-jquery-template">
<option value="${AreaCode}">${AreaCode}</option>
</script>
<br />
<script id="phoneNumberTemplate" type="text/x-jquery-template">
<div class="numberselectbox">
<strong>${FormattedPhoneNumber}</strong> Select<br/>
</div>
</script>
<div id="phoneNumbers">
</div>
Since you are using a template to generate the elements, these elements will be dynamic so you need to use delegated event model.
Also since it is a template, do not use static id for the elements since the elements can be duplicated - use class attribute instead
<script id="phoneNumberTemplate" type="text/x-jquery-template">
<div class="numberselectbox">
<strong>${FormattedPhoneNumber}</strong> Select<br/>
</div>
$(document).on('click', '.number', function(){
//do something
})
You could try jQuery's on() method or click() shorthand:
$(document).ready( function() {
$('#number').on('click', function(e){
// your method implementation here
e.preventDefault();
});
// OR //
$('#number').click(function(e){
// your method implementation here
e.preventDefault();
});
});

How to make two text boxes data accept jQuery data picker plugin?

Can you tell me of some good tutorial or some book where I can learn how to make a date picker text box?
Thank you.
P.S. In fact, I have to have two text boxes and one button that makes reservation when you select the above dates (From and To).
You could get some good tutorials here. A simple implementation of the jQuery UI DatePicker:
Javascript:
$(document).ready(function () {
$('.txtStartDate, .txtEndDate').datepicker({
showOn: "both",
dateFormat: 'dd/mm/yy',
showAnim: "slideDown",
showOptions: {
origin: ["top", "left"]
},
firstDay: 1,
changeFirstDay: false
});
});
Markup:
#model DateTime
#Html.TextBox("", Model.ToString("dd/MM/yyyy"), new { #class = "txtStartDate" })
#Html.TextBox("", Model.ToString("dd/MM/yyyy"), new { #class = "txtEndDate" })
Another option (similar to chridam's) is to define one class that you can use for all textboxes that require a date picker (assuming their options will be the same).
Razor:
#model DateTime
#Html.TextBox("", Model.ToString("dd/MM/yyyy"), new { #class = "date-picker" })
#Html.TextBox("", Model.ToString("dd/MM/yyyy"), new { #class = "date-picker" })
Javascript:
$(document).ready(function () {
$('.date-picker').datepicker({
//options...
});
});
Asp.Net
<form id="form1" runat="server">
<asp:TextBox ID="fromDate" runat="server" />
<asp:TextBox ID="toDate" runat="server" />
</form>
Jquery
var dates = $("#fromDate, #toDate").datepicker({
maxDate: '0',
changeMonth: true,
numberOfMonths: 1,
onSelect: function () { //write your code on selection}
});

Razor Jquery UI datepicker not working

I've read a lot of the questions on stackoverflow about this, tried some examples and am still stuck why this won't work. So I am asking the community.
MODEL:
public class UploadModel
{
public string PatientID { get; set; }
public DateTime DrawDate { get; set; }
}
Controller:
public class FileManagementController : Controller
{
[HttpGet]
public ActionResult UpLoad()
{
ViewData["message"] = String.Empty;
UploadModel model = new UploadModel
{
PatientID = String.Empty,
DrawDate = DateTime.Now,
};
return View(model);
}
[HttpPost]
public ActionResult Upload(UploadModel model, HttpPostedFileBase MyFile)
{
if (ModelState.IsValid)
{
//Do Validation and Save here
}
UploadModel newmodel = new UploadModel
{
PatientID = model.PatientID,
DrawDate = model.DrawDate,
};
ViewData["message"] = "data submitted";
return View(newmodel);
}
View:
<form action="" method="post" enctype="multipart/form-data" id="MyForm">
#Html.EditorFor(m => m)
<label for="MyDateTime">My Date Time:</label>
<label for="MyFile">File:</label>
<input type="file" name="MyFile" id="MyFile" /><br />
<input id="submit" name="submit" type="submit" value="Save" />
</form>
From there, I have added to the _Layout.cshtml page the following code (which all maps correctly)
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery-ui-1.7.2.custom.css")" rel="stylesheet" type="text/css" />
<script src='#Href("~/Scripts/jquery-1.7.1.js")' type="text/javascript" ></script>
<script src='#Href("~/Scripts/jquery-ui-1.8.1.custom.min.js")' type="text/javascript" ></script>
<script type="text/javascript" src='#Href("~/Scripts/jquery.alphanumeric.pack.js")'></script>
<script type="text/javascript" src='#Href("~/Scripts/jquery.watermark.min.js")'></script>
Then in Views -> Shared I have added an EditorTemplates folder and have created a DateTime.cshtml page that has:
#model DateTime
#Html.TextBox("", Model.ToString("dd/MM/yyyy"),
new { #class = "date" })
<script type="text/javascript" >
$(document).ready(function () {
//set the date picker
var dtp = '#ViewData.TemplateInfo.GetFullHtmlFieldId("")';
dtp = dtp.replace("[", "_");
dtp = dtp.replace("]", "_");
//window.alert($(dtp).attr("value"));
var hid = ($(dtp).attr("type") == "hidden");
if (!hid) {
$(dtp).datepicker({
showOn: 'button', buttonImage: '#Href("~/Content/images/calendar.gif")%>', buttonImageOnly: true
, changeMonth: true, changeYear: true
, dateFormat: 'dd M yy'//, numberOfMonths: 2
});
}
});
</script>
This seems to be the flavor of most of the tutorials on this, but don't seem to work. No icon appears. In Chrome I get the html5 calendar popup but never the jquery one. Any suggestions at all would be greatly appreciated.
The selector looks incorrect to me. You're code:
var dtp = '#ViewData.TemplateInfo.GetFullHtmlFieldId("")';
Would result in a string: 'my_id', but you still need to tell jQuery that string is an ID, using the # symbol like so:
var dtp = '##ViewData.TemplateInfo.GetFullHtmlFieldId("")';
As a side note, do you really want to export that entire Script tag for each rendered DateTime in your model? Seems unnecessary to me, but you may have already thought about this. My recommendation would be to modify your DateTime.cshtml to simply:
#model DateTime
#Html.TextBox("", Model.ToString("dd/MM/yyyy"), new { #class = "date-picker" })
Then somewhere in your page or Layout, something like:
<script type="text/javascript" >
$(function () {
$('.date-picker').datepicker({
showOn: 'button', buttonImage: '#Href("~/Content/images/calendar.gif")%>', buttonImageOnly: true
, changeMonth: true, changeYear: true
, dateFormat: 'dd M yy'//, numberOfMonths: 2
});
});
</script>
That way, just one script is rendered and all your DateTime's are taken care of.
Since I'm a noob I can't post a comment (sorry!), but the only advice I can give is to make sure that the html derived from #Html.EditorFor(m => m) is exactly what you need (this html is different depending on the model). Here's more info about that: http://msdn.microsoft.com/en-us/library/ee402949(v=vs.98).aspx
Also, I noticed in the javascript section you have a %> at the end here: "#Href("~/Content/images/calendar.gif")%>" and it looks like an error.

Categories

Resources