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

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}
});

Related

How to get autocompletet textbox Locations from google API in mvc?

I am using MVC and in View i want to bind a textbox to google API to get auto complete address, How to do this in MVC??
Note: I dont want to display google maps. just textbox show suggestions .. I Did something like this
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAacPaT9YiOu-8leoacd1RDbRfx7an1u74&libraries=places&callback=initMap"
async defer></script>
<script>
google.maps.event.addDomListener(AddNewJob, 'load', function () {
var options = {
types: ['(cities)'],
componentRestrictions: { country: "in" }
};
});
autocomplete = new google.maps.places.Autocomplete(document.getElementById('FromAddress'));
autocomplete.addListener();
</script>
}
And in textBox
<div class="form-group">
#Html.LabelFor(model => model.FromAddress, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="text" id="FromAddress" />
#Html.ValidationMessageFor(model => model.FromAddress, "", new { #class = "text-danger" })
</div>
</div>
var input = document.getElementById('your input tag id');
var autocomplete = new google.maps.places.Autocomplete(input);
Use javascript to do it. Follow api documentation
Check it out on jsfiddle
To do this, you'll need a Maps API Key which you can obtain here : https://developers.google.com/maps/documentation/embed/get-api-key.
Replace YOUR_API_KEY in the scripts url with the api key you obtain from the link above.
Change the id to match the id of the input element you want to attach this to. In the example below, the input element's id is "FromAddress".
And you might want to change options or remove it entirely depending on your needs as the current setting limits the auto-completion to cities in India.
#section Scripts {
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async="" defer=""></script>
<script>
function initMap() {
google.maps.event.addDomListener(window, 'load', function () {
var options = {
types: ['(cities)'],
componentRestrictions: { country: "in" }
};
var input = document.getElementById('FromAddress');
var places = new google.maps.places.Autocomplete(input, options);
});
}
</script>
}

Add Validation Rules Dynamically to MVC3

All,
I need to add validation rules to dynamic form input text elements added by the user.
I am accomplishing this by cloning a chunk of HTML, providing unique ids and adding to the DOM
I researched the syntax for this, which I believe is correct yet I am getting the following JS error when I try to access the .rules method:
TypeError: $(...).rules is not a function
Caused by this:
$("input[type=text].validateRequired").each(function () {
$(this).rules("add", { required: true, messages: { required: "Data is missing" }
});
});
When I examine $(this) in FireBug, I do not see a .rules method yet it exists in the validation scripts and all of the documentation shows that the method should be available globally. Not sure how to get it in scope.
Here are the code pieces in the View related to this problem:
JS Includes
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
JS Method that creates the dynamic form elements
<script type="text/javascript">
$(document).ready(function() {
var uniqueId = 1;
var ctr = 1;
$(function() {
$('.js-add-cosponsor-hyperlink').click(function() {
var copy = $("#cosponsorsTemplate").clone(true).appendTo("#addCosponsorSection").hide().fadeIn('slow');
var cosponsorDivId = 'cosponsors_' + uniqueId;
var copyText = copy.html();
copyText = copyText.replace(/Guitar1/g, 'Guitar' + ctr);
copyText = copyText.replace('Guitar_1', 'Guitar_' + ctr);
copy.html(copyText);
$('#cosponsorsTemplate').attr('id', cosponsorDivId);
var deleteLink = copy.find("a.icon.delete");
deleteLink.on('click', function() {
copy.fadeOut(300, function() { $(this).remove(); }); //fade out the removal
});
$.validator.unobtrusive.parse(form);
$("input[type=text].validateRequired").each(function () {
var t = $(this);
$(this).rules("add", { required: true, messages: { required: "Data is missing" } });
});
uniqueId++;
ctr++;
});
});
});
</script>
*The Form*
#using (Html.BeginForm())
{
[...]
<!-- Template used to do the Clone: These need dynamic validation -->
<div style="display:none">
<div id="cosponsorsTemplate">
<div class="formColumn1"><label>Guitar</label></div>
<div class="formColumn2">#Html.TextBoxFor(model => model.Guitar1.Make, new { Placeholder = "Make", Class = "validateRequired" })
<div class="messageBottom">
#Html.ValidationMessageFor(model => model.Guitar1.Make)
</div>
</div>
<div class="formColumn3">#Html.TextBoxFor(model => model.Guitar1.Model, new { Placeholder = "Model" , Class = "validateRequired"})
<div class="messageBottom">
#Html.ValidationMessageFor(model => model.Guitar1.Model)
</div>
</div>
<div class="formColumn4">#Html.TextBoxFor(model => model.Guitar1.ProductionYear, new { Placeholder = "Production Year", Class = "validateRequired" })
<div class="messageBottom">
#Html.ValidationMessageFor(model => model.Guitar1.ProductionYear)
</div><a class="icon delete">Delete</a>
</div>
</div>
</div>
<!-- End Add Co-Sponsor Row Template -->
}
You are cloning a chunk of HTML so every time you do a clone you need to parse the whole form
by using $.validator.unobtrusive.parse

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();
});
});

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.

How to use TimePicker to DatePicker MVC3 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>

Categories

Resources