Tempus Dominus Timepicker show time after selecting date - asp.net-mvc

I am using the Tempus Dominus Timepicker v5.0.1 with jquery 3.4.1 and the latest version of moment.js. I have a form that has a registration start date and time and a registation end date and time. I want the user to be able to select the date and after they click a date I want the time to appear automatically (the equivalent of clicking the clock button at the bottom).
I have my view:
<div class="form-row">
<div class="col-md-4 col-lg-3 mb-3">
#Html.LabelFor(m => m.RegistrationStartDate, new { #class = "font-weight-bold label-required" })
#Html.TextBoxFor(m => m.RegistrationStartDate, new { #class = "form-control datetimepicker-input", placeholder = RecruitClassResource.RegistrationStartDate, required = "required", id="datetimepicker1", data_toggle="datetimepicker", data_target="#datetimepicker1" })
#Html.ValidationMessageFor(m => m.RegistrationStartDate)
</div>
</div>
<div class="form-row">
<div class="col-md-4 col-lg-3 mb-3">
#Html.LabelFor(m => m.RegistrationEndDate, new { #class = "font-weight-bold label-required" })
#Html.TextBoxFor(m => m.RegistrationEndDate, new { #class = "form-control datetimepicker-input", placeholder = RecruitClassResource.RegistrationEndDate, required = "required", id="datetimepicker2", data_toggle="datetimepicker", data_target="#datetimepicker2" })
#Html.ValidationMessageFor(m => m.RegistrationEndDate)
</div>
</div>
javascript:
#section Scripts {
#Scripts.Render("~/Scripts/moment.min.js")
#Scripts.Render("~/Scripts/tempusdominus-bootstrap-4.js")
<script>
$(document).ready(function () {
$('.datetimepicker-input').datetimepicker({
icons: {
time: "far fa-clock"
}
});
$('.datetimepicker-input').on('change.datetimepicker', function (e) {
// Just a test to see when this event is fired
alert(e.date);
});
});
</script>
}
I thought maybe the change.datetimepicker would be the event listener I was looking for, but it is fired the first time I click the textbox because the value changes from null to the current date. I also am not sure what I would need to call for the time to appear when a date is selected.

I have a JSFiddle for you, which does what you want, my friend -> https://jsfiddle.net/8ta5j6v7/2/.
Here is the code:
<div class="container" style="padding: 80px;">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<div class="input-group date" id="datetimepicker1" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1" />
<div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
</div>
</div>
</div>
$(function() {
$("#datetimepicker1").datetimepicker();
var $picker = $("#datetimepicker1");
$picker.on("change.datetimepicker", function (e) {
// After the date is selected, I would like to switch to time view automatically / programmatically
if (!e.oldDate && $picker.datetimepicker('useCurrent')) {
// First time ever. If useCurrent option is set to true (default), do nothing
// because the first date is selected automatically.
return;
}
else if (
e.oldDate &&
e.date &&
(e.oldDate.format('YYYY-MM-DD') === e.date.format('YYYY-MM-DD'))
) {
// Date didn't change (time did).
return;
}
setTimeout(function () {
$('#datetimepicker1 [data-action="togglePicker"]').click();
}, 300); // With a mini delay so that the animation doesn't fire right-away.
});
});

Related

remote validation does not work for partial view

I have order with several order items and I use partial view to load order items. I want to validate OrderLineItemEntity's ProductCode but it does not work. Every other property validation works which is not in partial view. How can I force to validate partial view too?
Order View:
<div id="orderLineItemsContainer" class="form-group">
#Html.EditorFor(model => model.OrderLineItems)
</div>
OrderLineItems View:
#model SalesManagementSystem.Models.OrderEntity
#Html.EditorFor(model => model.OrderLineItems)
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
OrderLineItem View:
#model SalesManagementSystem.Models.OrderLineItemEntity
<div class="form-inline col-md-12" style="margin-bottom: 5px">
<div class="form-group col-md-6">
#Html.LabelFor(model => model.ProductCode, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.ProductCode, new { htmlAttributes = new { #class = "form-control", id = "ProductCode" } })
#Html.ValidationMessageFor(model => model.ProductCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group col-md-6">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { #class = "form-control", id = "ProductQuantity" } })
#Html.ValidationMessageFor(model => model.Quantity, "", new { #class = "text-danger" })
</div>
</div>
#if (Model != null)
{
<a onclick="deleteRow('#Model.ProductCode')">Delete</a>
}
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
ValidationController:
public JsonResult IsProductCodeValid(int ProductCode){...}
This is how I update my order items when new item is added. I think I need to add something here.
$("#btnAdd").click(function () {
var order = {
'Id': $("#Id").val(),
'Date': $("#Date").val(),
'ConsultantId': $("#ConsultantId").val(),
'OrderLineItems': getOrderLineItems()
};
$.ajax({
url: '#Url.Action("AddOrderItem", "Orders")',
type: "POST",
data: {
order: order
},
success: function (partialView) {
$("#orderLineItemsContainer").html(partialView);
},
failure: function (response) {
alert("failed");
}
});
});
Update:
I tried adding
jQuery.validator.unobtrusive.parse("#ProductCode");
And
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
Still not working
you can add a name and id (like ProductForm) property to your partial view form
after that, in cshtml file's script section
you can add a screen control method like this
function ScreenControl() {
if ($('#ProductForm')[0].checkValidity()) {
// do what do you want
} else {
$("#btnSave2").click();
}
}
and you should add 2 buttons to bottom of the form, one of them should be hidden like
<label class="col-md-1 control-label"></label>
<div class="col-md-1">
<button class="btn btn-sm btn-primary" style="float: right" type="button" id="btnSave" name="btnSave" value="Save" onclick="ScreenControl()">
<i class="fa fa-save"></i>
Save
</button>
</div>
<button class="btn btn-sm btn-primary" type="submit" id="btnSave2" name="btnSave2" value="Save" style="display: none">
<i class="fa fa-save"></i> Save
</button>

mvc radiobuttonfor in editortemplate keyboard navigation does not set model

Context:
Model generating some RadioButtonFor groupings as input to answer questions.
What is happening:
Case 1. When mouse click on a radio option the display looks correct. When the [HttpPost] ActionResult(model) for the page is triggered the Model.Answer comes through with the correct value. Which is good and desired.
Case 2. When navigating with the keyboard to the radio group and selecting one with arrow keys the display looks correct. But when the [HttpPost] ActionResult (model) is triggered the Model.Answer value is unchanged from what it was loaded as on page load.
Here is the code that makes the radio group:
#model NexusPWI.ViewModels.Wizard.QuestionModel
#* Dynamically generate and model bind controls for QuestionModel *#
#{
<div class="row d-contents">
<div class="form-group">
<div class="question">
<div class="col-lg-2 d-contents">
<div class="btn-group btn-toggle group-sm d-contents" data-toggle="buttons">
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.Yes ? "active" : "")" for="#Model.Answer">
#YesNoNAOptions.Yes.ToString().ToUpper()
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.Yes, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.No ? "active" : "")" for="#Model.Answer">
#YesNoNAOptions.No.ToString().ToUpper()
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.No, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
#if (!Model.NaInvalid)
{
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.NA ? "active" : "")" for="#Model.Answer">
N/A
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.NA, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
}
</div>
</div>
<div class="col-lg-9 d-contents">
<div class="row">
<p>
<strong>#Model.Question</strong>
</p>
</div>
#Html.HiddenFor(x => Model.Question_IdentityMarker, new { #class = "Question_IdentityMarker" })
</div>
</div>
</div>
</div>
}
Here is an example of the html that is generated:
<div class="form-group">
<div class="question">
<div class="col-lg-2 d-contents">
<div class="btn-group btn-toggle group-sm d-contents" data-toggle="buttons">
<label class="btn QuestionRadio btn-default " for="No">
YES
<input data-val="true" data-val-required="The Answer field is required." id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="Yes" type="radio">
</label>
<label class="btn QuestionRadio btn-default active" for="No">
NO
<input checked="checked" id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="No" type="radio">
</label>
<label class="btn QuestionRadio btn-default " for="No">
N/A
<input id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="NA" type="radio">
</label>
</div>
</div>
<div class="col-lg-9 d-contents">
<div class="row">
<p>
<strong>Do you charge sales tax?</strong>
</p>
</div>
<input class="Question_IdentityMarker" id="Questions_0__Question_IdentityMarker" name="Questions[0].Question_IdentityMarker" value="CUSTOMERSALESTAX" type="hidden">
</div>
</div>
</div>
EDIT Adding onFocus & onBlur at request:
onFocus & onBlur are css highlighting for the keyboard navigation to make it more clear for the user where they are in the page.
function radiofocus(event) {
// Get event object if using Internet Explorer
var e = event || window.event;
// Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element
if (e.target) {
var addClass = focusClass(e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r");
e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass;
} else {
var addClass = focusClass(e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r");
e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass;
}
};
function radioblur(event) {
// Get event object if using Internet Explorer
var e = event || window.event;
var removeClass = focusClass("", "r").trim();
// Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element
if (e.target) {
e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, "");
} else {
e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, "");
}
};
Why do the keyboard navigated changes not get back to the controller?
Anything to add to make this clearer?
Side note: For some reason before a value is chosen in the radio group the keyboard tab navigation is stopping for each radio answer for a question.

bootstrap modal to appear when dropdownlist item is selected in mvc

I want a bootstrap modal with partial view to popup when a user selects the dropdownlist item.
For each selected item the popup should refresh with new content when the user selects a different item in the dropdownlist. From the code below, I could able to make the ajax and then redirect to partial view with model values but unable to display the modal popup
Index.cshtml
<div class="form-group">
#Html.LabelFor(model => model.SelectedIssue, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.DropDownListFor(model => model.SelectedIssue, Model.IssueDetails, "Please Select", new { #class = "form-control", #id = "IssueId" })
#Html.ValidationMessageFor(model => model.SelectedIssue, "", new { #class = "text-danger" })
</div>
</div>
$("#IssueId").change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("GetActionDetails")',
dataType: 'html',
data: { id: $("#IssueId").val() },
success: function (data) {
$('#modal-content').html(data);
$('#modal-container').modal('show');
},
error: function (ex) {
alert('Failed to retrieve action details' + ex);
}
});
return false;
});
The dropdown selection is making an ajax call and calling the below method in the controller
public ActionResult GetActionDetails(string id)
{
ActionDetails model = new ActionDetails();
model.ActionTaken = "Action Taken ";
model.AdviceGiven = "Advice Given to";
return PartialView("ActionDetails", model);
}
This is then redirecting to PartialView ActionDetails view which is below.
#model OnCallLogging.Models.ActionDetails
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 class="modal-title">Action Details</h3>
</div>
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(m => Model.ActionTaken, new { #class = "control-label col-sm-3"})
<div class="col-sm-9">
#Html.DisplayFor(m => m.ActionTaken, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => Model.AdviceGiven, new { #class = "control-label col-sm-3" })
<div class="col-sm-9">
#Html.DisplayFor(m => m.AdviceGiven, new { #class = "form-control" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-warning" data-dismiss="modal">Close</button>
</div>
And in the Layout.cshtml, the following markup is written before the body closing tag.
<div id="modal-container" class="modal fade hidden-print" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
and in the script.css
.modal-content {
width: 600px !important;
margin: 30px auto !important;
}
When I run the code, the screen goes dim but no popup appears. When I debug I could see ajax calling the controller action and redirecting to partial view, but the popup does not appear.
Not sure what am I missing to show the popup with model properties. Could anyone please help.
Since you are seeing the controller action being called while debugging, the harder part is working. The most likely explanation for your issue is in your javascript "success:":
//change from this:
$('#modal-content').html(data);
//to this:
$('.modal-content').html(data);
You can optionally, change your <div class="modal-content"> to <div id="modal-content">

two submit buttons for different form within the same view and controller

I have a view screen that has two different form on it, that will be activated differently. if the first button is clicked, the first form comes up and the user can fill and submit after which he proceed to click the other button to activate the other form which will then be submitted to a different table. I tried giving it different each submit button different name but my controller isn't recognizing the name. any help will be appreciated.
this is my view presently
<div class="container">
<form class="form-horizontal" role="form" method="post" id="head">
<div class="form-group">
<label for="warehouse" class="col-sm-2 control-label">Transaction type</label>
<div class="col-sm-7">
#Html.TextBoxFor(m => m.vwint0, ViewBag.action_flag == "Create" ? (object)new { #class = "form-control", style = "width : 120px", #maxlength = 10 } : new { #disabled = "disabled", style = "width : 120px" })
#Html.ValidationMessageFor(m => m.vwint0)
</div>
</div>
<div class="form-group">
<label for="code" class="col-sm-2 control-label">Customer code</label>
<div class="col-sm-7">
#Html.DropDownListFor(m => m.vwstring1, ViewBag.cus as SelectList, "Select", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button type="submit" class="btn btn-primary" name="update" value="headsub">Submit</button>
</div>
</div>
</form>
<form class="form-horizontal" role="form" method="post" id="details">
<div class="form-group">
<label for="firstName" class="col-sm-2 control-label">Sale sequence number </label>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.vwint0, new { #class = "form-control", style = "width : 80px", maxlength = 10 })
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Quote sequence</label>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.vwstring9, new { #class = "form-control", style = "width : 80px", maxlength = 10 })
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Item code</label>
<div class="col-sm-9">
#Html.DropDownListFor(m => m.vwstring10, ViewBag.item as SelectList, "Select", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button type="submit" class="btn btn-primary" name="update" value="detailsub">Submit</button>
</div>
</div>
</form>
</div>
In my controller, I tried this but my controller isn't even recognizing the button name.
if (update == "headsub")
{
AR_002_SALES gdoc = new AR_002_SALES();
gdoc.sale_sequence_number = glay.vwint0;
gdoc.customer_code = glay.vwstring1;
gdoc.currency_code = glay.vwstring2;
}
else
{
AR_002_QUOTE = new AR_002_QUOTE();
AR_002_QUOTE.sale_sequence_number = glay.vwint0;
AR_002_QUOTE.quote_sequence = glay.vwstring9;
AR_002_QUOTE.item_code = string.IsNullOrWhiteSpace(glay.vwstring10) ? "" : glay.vwstring10;
AR_002_QUOTE.quote_qty = glay.vwdclarray0[0];
AR_002_QUOTE.price = glay.vwdclarray0[1];
}
Instead of using <form class="form-horizontal" role="form" method="post" id="head">
use #using (Html.BeginForm("ActionMethod", "Controller", FormMethod.Post, new { #class = "form-horizontal" ,#id="head" }))
to submit a form and action method will process that form and does stuff.Similarly you can do for another form also.
In your .cshtml it looks like it will not hit any action method of that controller.

Bootstrap Switch: On change set specific DropDownList to blank?

I am using BootStrap Switch to show/hide certain s based on the Switch value. When I need to ensure (for my Controller postback) is that when a switch is made, the DropDownList being hidden has it's value reset to blank or null. I need to ensure that a user can only select a value for Member Organizations or Sponsors, not for both.
I however can't seem to figure out how to reference a specific DropDownList control in my javascript (still fairly new to MVC development). Anyone have thoughts on the matter?
HTML
<div style="margin-bottom: 15px">
<div class="row switchOn">
<div class="editor-label">
#Html.LabelFor(model => model.MemberOrgId, "Organization")
</div>
<div class="editor-field">
#Html.DropDownList("OrganizationId", null, String.Empty, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MemberOrgId)
</div>
</div>
<div class="row switchOff">
<dliv class="editor-label">
#Html.LabelFor(model => model.SponsorOrgId, "Sponsor")
</dliv>
<div class="editor-field" >
#Html.DropDownList("SponsorId", null, String.Empty, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SponsorOrgId)
</div>
</div>
</div>
jQuery
<script type="text/javascript">
jQuery(document).ready(function () {
setTimeout(function () { $("#alert").alert('close'); }, 5000);
$('.switchOff').addClass('hide');
});
$.fn.bootstrapSwitch.defaults.onText = 'Member';
$.fn.bootstrapSwitch.defaults.offText = 'Sponsor';
$.fn.bootstrapSwitch.defaults.offColor = 'info';
$.fn.bootstrapSwitch.defaults.animate = false;
//$.fn.bootstrapSwitch.defaults.size = 'large';
$(document).ready(function () {
$('input:checkbox[name="Sponsor-Organization"]').bootstrapSwitch();
});
$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function (event, state) {
var checked = state;
if (checked) {
$('.switchOn').removeClass('hide');
$('.switchOff').addClass('hide');
}
else {
$('.switchOff').removeClass('hide');
$('.switchOn').addClass('hide');
}
});
$(document).ready(function () {
$(".btn-danger").click(function () {
var cancel = confirm("Are you sure? Entered data will be lost.")
if (cancel != true) {
event.preventDefault(); // cancel the event
}
});
});
//$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function(event, state) {
</script>
Added an ID to each dropdown and then reference it in my jQuery.
<div style="margin-bottom: 15px">
<div class="row switchOn">
<div class="editor-label">
#Html.LabelFor(model => model.MemberOrgId, "Organization")
</div>
<div class="editor-field">
#Html.DropDownList("OrganizationId", null, String.Empty, new { #class = "form-control", #id = "OrgIdDropDown" })
#Html.ValidationMessageFor(model => model.MemberOrgId)
</div>
</div>
<div class="row switchOff">
<dliv class="editor-label">
#Html.LabelFor(model => model.SponsorOrgId, "Sponsor")
</dliv>
<div class="editor-field" >
#Html.DropDownList("SponsorId", null, String.Empty, new { #class = "form-control", #id = "SponsorIdDropDown" })
#Html.ValidationMessageFor(model => model.SponsorOrgId)
</div>
</div>
</div>
jQuery:
$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function (event, state) {
var checked = state;
if (checked) {
$('.switchOn').removeClass('hide');
$('.switchOff').addClass('hide');
$('#SponsorIdDropDown').val("");
}
else {
$('.switchOff').removeClass('hide');
$('.switchOn').addClass('hide');
$('#OrgIdDropDown').val("");
}
});

Resources