I am trying to show a datepicker calendar in each row of table . But it shows only first row. When I add new row in a table, the datepicker is not showed newly added rows.
Model class
[DataType(DataType.Date, ErrorMessage = "Date only")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public string FromDate { get; set; }
[DataType(DataType.Date, ErrorMessage = "Date only")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public string ToDate { get; set; }
Html file
<table>
<tbody>
<tr>
<td>#Html.TextBoxFor(model => model.FromDate, new { #class = "form-control" })</td>
<td>#Html.TextBoxFor(model => model.ToDate, new { #class = "form-control" })</td>
</tr>
</tbody>
</table>
<button type="button" id="btnUpdate" name="submitButton" value="DeleteAtt"
class="btn btn-primary form-control" onclick="AddNew();">
<i class="fa fa-save"></i><span class="padding-left-ten">Add New Row</span>
</button>
<script type="text/javascript">
$(document).ready(function () {
$("#FromDate").datepicker({ format: 'dd/mm/yyyy', todayHighlight: true, date: new Date(), autoclose: true, todayBtn: 'linked' });
$("#ToDate").datepicker({ format: 'dd/mm/yyyy', todayHighlight: true, date: new Date(), autoclose: true, todayBtn: 'linked' });
});
function AddNew() {
var clone = $("#tblEntry tr:last").clone().find('input').val('').end().insertAfter("#tblEntry tr:last");
}
</script>
First, you'll need to stop duplicating id values in your HTML. Those need to be unique across the DOM, otherwise your selectors will have no way to identify multiple elements with the same id. Instead, assign a class that you can recognize for the date inputs. For example:
<td>#Html.TextBoxFor(model => model.FromDate, new { #class = "form-control date-input" })</td>
#Html.TextBoxFor(model => model.ToDate, new { #class = "form-control date-input" })
Note the new "date-input" class values. Then use those to initialize the datepicker plugin:
$(document).ready(function () {
$(".date-input").datepicker({ format: 'dd/mm/yyyy', todayHighlight: true, date: new Date(), autoclose: true, todayBtn: 'linked' });
});
Second, it's important to understand that this will only initialize the datepicker plugin for elements which exist when this code executes, which is only once when the page loads. Any elements added afterward would also need to have the plugin initialized at that time. So you'd do that in your AddNew function:
function AddNew() {
var clone = $("#tblEntry tr:last").clone().find('input').val('').end().insertAfter("#tblEntry tr:last");
$(clone).find(".date-input").datepicker({ format: 'dd/mm/yyyy', todayHighlight: true, date: new Date(), autoclose: true, todayBtn: 'linked' });
}
If you like, you can reduce the repeated use of the datepicker plugin configuration by extracting that into its own function. Perhaps something like this:
function initDatepicker(selection) {
selection.datepicker({ format: 'dd/mm/yyyy', todayHighlight: true, date: new Date(), autoclose: true, todayBtn: 'linked' });
}
Then you'd call it in both places with your selected jQuery results:
$(document).ready(function () {
initDatepicker($(".date-input"));
});
and:
function AddNew() {
var clone = $("#tblEntry tr:last").clone().find('input').val('').end().insertAfter("#tblEntry tr:last");
initDatepicker($(clone).find(".date-input"));
}
Related
Let's say I have the following.
#Html.DropDownListFor(m => m.MyWebPage, Model.FruitsList, "Select", htmlAttributes: new { #class = "form-select detailsInfo" })
And within this drop down menu I have a selection that says "Custom" and right after that drop down I have a textbox that is autopopulated with the user's already selected option
#Html.TextBoxFor(m => m.MyWebPage, htmlAttributes: new { #class = "form-control", id="CustomFruitTextBox"})
What would I have to call in order to disable the text box if the drop down selection is not currently selected to "Custom"?
Would this require javascript or could I do this in the razor file manually?
You can try to use js to check the selected value of the dropdown:
view:
#Html.DropDownListFor(m => m.MyWebPage, Model.FruitsList, "Select", htmlAttributes: new { #class = "form-select detailsInfo" #onchange="check()" })
js:
<script>
$(function () {
check();
})
function check() {
if ($("#MyWebPage").val() != "Custom") {
$("#CustomFruitTextBox").attr("disabled", "disabled");
} else{
$("#CustomFruitTextBox").removeAttr("disabled");
}
}
</script>
I am trying to set the value for Html.TextBoxFor field in an ASP.NET MVC 5 view. The TextBoxFor is defined in the following manner within the view:
<div>
#Html.LabelFor(model => model.ServicePoints, htmlAttributes: new { #class = "control-label LabelStyle1 row-spacing" })
<div>
#Html.TextBoxFor(model => model.ServicePoints, new { htmlAttributes =
new { #class = "form-control",
#type = "number", #min = "1", #step = "1", #id = "idQty"} })
#Html.ValidationMessageFor(model => model.ServicePoints, "", new { #class = "text-danger" })
</div>
<div id="idButtonArea">
<input type="button" id="idTestBtn" value="Test" class="btn btn-primary" />
</div>
</div>
The model with the ServicePoints property is defined as follows:
public class TestPersonModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int ServicePoints { get; set; }
public TestPersonModel()
{
ServicePoints = 2;
}
}
After attempting to set the value of the TextBoxFor field I read it back and get an "undefined" value returned so it looks like I am not successfully setting the value. The TextBoxFor field is also not showing the value I am trying to set using the button in the view which tries to set a value of 3. Below is the JQuery I am using with the problem:
<script>
$("#idButtonArea").on('click', '#idTestBtn', function () {
$('#idQty').val(3);
var aValue = $('#idQty').val();
alert("Service Pionts: " + aValue);
});
</script>
The MVC Controller used to support this view is shown below:
[AllowAnonymous]
public ActionResult TestForPo()
{
TestPersonModel testPersonModel = new TestPersonModel();
return View(testPersonModel);
}
The full view is shown below:
#model rgmsite.Models.TestPersonModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>TestForPo</title>
</head>
<body>
<div>
#Html.LabelFor(model => model.ServicePoints, htmlAttributes: new { #class = "control-label LabelStyle1 row-spacing" })
<div>
#Html.TextBoxFor(model => model.ServicePoints, new { htmlAttributes =
new { #class = "form-control",
#type = "number",
#min = "1",
#step = "1",
#id = "idQty"} })
#Html.ValidationMessageFor(model => model.ServicePoints, "", new { #class = "text-danger" })
</div>
<div id="idButtonArea">
<input type="button" id="idTestBtn" value="Test" class="btn btn-primary" />
</div>
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script>
$("#idButtonArea").on('click', '#idTestBtn', function () {
$('#idQty').val(3);
var aValue = $('#idQty').val();
alert("Service Pionts: " + aValue);
});
</script>
</body>
</html>
What am I missing or doing wrong here to set the value of the TextBoxFor field? Any feedback is much appreciated. Thank you and advance.
You have redundant htmlAtributes change it to
#Html.TextBoxFor(model => model.ServicePoints, new {
#class = "form-control",
#type = "number",
#min = "1",
#step = "1",
#id = "idQty" })
hello i'm tryinh to change simple input to date form i tried text
to show a datetime picker with DateTime property
but when i use
#Html.TextBoxFor(model => model.dateFin, new { type = "date" })
but it doesn't work
so i'm using simple input
#Html.EditorFor(model => model.dateDebut, new { htmlAttributes = new {#class = "form-control" } })
#Html.ValidationMessageFor(model => model.dateFin, "", new { #class = "text-danger" })
is there someone who's familiar with this form ?
You can create custom html helper control for datepicker like
public static class HtmlHelper
{
public static IHtmlString DatePicker(this HtmlHelper helper, string id)
{
TagBuilder input = new TagBuilder("input");
input .Attributes.Add("type", "date");
input .Attributes.Add("id", id);
return new MvcHtmlString(input.ToString());
}
}
After creating, you need to refer to this class in your razor page with #using. And you can use like #Html.DatePicker("dt1")
I am trying to disable/enable an #Html.TextBoxFor in razor using an #Html.CheckBoxFor
I have defined my CheckBoxFor in this manner:
#Html.CheckBoxFor(m => m.ResYearChecked, new { Name = "ResYearChecked", id = "ResYearChecked" })
#Html.TextBoxFor(m => m.SearchResYear, new { Name = "SearchResYear", id = "SearchResYear" })
and I am trying to call the script:
<script>
$('ResYearChecked').change(function () {
$("SearchResYear").prop("disabled", !$(this).is(':checked'));
});
</script>
Do I need to add the onclick attribute to the CheckBoxFor?
I was able to figure out the solution. I enabled the attribute readonly for the #Html.TextBoxFor. I then removed the readonly attribute once the #Html.CheckBoxFor was checked.
Here is the code for my #Html.CheckBoxFor and #Html.TextBoxFor
#Html.CheckBoxFor(m => m.ResYearChecked, new { Name = "ResYearChecked", id = "ResYearChecked" })
#Html.TextBoxFor(m => m.SearchResYear, new { Name = "SearchResYear", id = "SearchResYear", #readonly = "readonly" })
Here is the JavaScript
<script>
$('#ResYearChecked').change(function () {
if ($(this).is(":checked")) {
$("#SearchResYear").removeAttr("readonly");
$("#SearchResYear").focus();
} else {
$("#SearchResYear").attr("readonly", "readonly");
}
});
</script>
I have a big trouble with pasting a value in Kendo DateTimePicker inside Kendo Grid from json result. So I have two forms on page. In first I'm loading file:
#using (Html.BeginForm("GetImportSalesModelFromFile", "ExportImport", FormMethod.Post, new { id = "GetImportSaleModelFromFileForm", enctype = "multipart/form-data" }))
{
<input id="importFileInput" type="file" accept="text/csv" name="file" class="user-success" required>
<input style="width: 100px;" type="submit" value="Add">
}
On form submit called function
$('#GetImportSaleModelFromFileForm').submit(function(e) {
e.preventDefault();
var url = $(this).attr('action');
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("file", document.getElementById('importFileInput').files[0]);
xhr.open("POST", url, true);
xhr.send(fd);
xhr.addEventListener("load", function(event) {
AppendImportModel(JSON.parse(event.target.response));
}, false);
});
In controller I get needed import model
public ActionResult GetImportSalesModelFromFile(HttpPostedFileBase file)
{
var importModel = _importService.ConstructSaleImportModel(file.InputStream, file.ContentType);
return Json(importModel, JsonRequestBehavior.AllowGet);
}
In function AppendImportModel I parse result and paste it in kendo grid in second form
#(Html.Kendo().Grid<ImportSaleItemModel>().Name("ImportSalesGrid")
.DataSource(dataSource => dataSource.Ajax())
.Events(x => x.DataBound("initMenus"))
.Columns(columns =>
{
columns.Bound(x => x.Goods.PictureId)
.ClientTemplate("<img style='height: 50px;' src='" + Url.Action("Contents", "FileStorage", new { id = "#= Goods.PictureId #" }) + "'/>")
.Title("")
.Sortable(false)
.HtmlAttributes(new Dictionary<string, object> { { "style", "padding: 3px !important; height: 52px !important; width:52px !important;" } });
columns.Bound(x => x.Goods.Title)
.ClientTemplate("<a onclick='ShowInfoGoodWindow(#= Goods.Id #)'>#= Goods.Title #</a><br>" +
"<span><b>#= Goods.Article #</b> <descr>#= Goods.Description #</descr></span><br><input type='hidden' name='ImportedGoodList[#= index(data)#].Id' value='#= Goods.Id #' />")
.Title("Description");
columns.Bound(x => x.Price)
.ClientTemplate("<input class='priceEditor' maxlength='10' style='width:50px; text-align: center;' type='text' name='ImportedGoodList[#= index(data)#].Price' onkeypress='return isPriceKey(event)' oninput='$(this).get(0).setCustomValidity(clearValidation);' value='#=Price.ParsedValue #'>")
.HtmlAttributes(new Dictionary<string, object> { { "style", "text-align: center;" } })
.Title("Price");
columns.Bound(x => x.Discount)
.ClientTemplate("<input class='discountEditor' maxlength='10' style='width:50px; text-align: center;' type='text' name='ImportedGoodList[#= index(data)#].Discount' onkeypress='return isPriceKey(event)' oninput='$(this).get(0).setCustomValidity(clearValidation);' value='#=Discount.ParsedValue #'>")
.HtmlAttributes(new Dictionary<string, object> { { "style", "text-align: center;" } })
.Title("Discount");
columns.Bound(x => x.DepartmentId)
.HtmlAttributes(new { #class = "templateCell" })
.ClientTemplate(Html.Kendo().DropDownList().Name("Department#=LineId#").BindTo(Model.Departments).Value("#= DepartmentId #").ToClientTemplate().ToHtmlString())
.Title("Department");
columns.Bound(x => x.SaleDateTime)
.HtmlAttributes(new { #class = "templateCell" })
.ClientTemplate(Html.Kendo().DateTimePicker().Name("SaleDateTime#=LineId#").Value("#= ConvertedSaleDateTime #").ToClientTemplate().ToHtmlString())
.Title("Sale Date");
columns.Bound(x => x.SellerId)
.HtmlAttributes(new { #class = "templateCell" })
.ClientTemplate(Html.Kendo().DropDownList().Name("Seller#=LineId#").BindTo(Model.Sellers).Value("#= SellerId #").ToClientTemplate().ToHtmlString())
.Title("Seller");
columns.Bound(x => x.IsCashPayment)
.ClientTemplate("<input type='checkbox' id='IsCashPayment#=LineId#' checked='#= IsCashPayment.ParsedValue #' class='regular-checkbox'/><label for='IsCashPayment#=LineId#'></label> Yes")
.Title("Is Cash Payment");
})
)
In all columns using "#= value #" works fine but not in this line
.ClientTemplate(Html.Kendo().DateTimePicker().Name("SaleDateTime#=LineId#").Value("#= ConvertedSaleDateTime #").ToClientTemplate().ToHtmlString())
"#= ConvertedSaleDateTime #" not changed on real value, but if I write
.ClientTemplate("#= ConvertedSaleDateTime #")
I will get right value "10/07/2013 13:15". And if I write
.ClientTemplate(Html.Kendo().DateTimePicker().Name("SaleDateTime#=LineId#").Value("10/07/2013 13:15").ToClientTemplate().ToHtmlString())
I will get Kendo DateTimePicker inside grid with value "10/07/2013 13:15"
How I can set value to this DateTimePicker from ConvertedSaleDateTime?
Please, help me. Thanks in advance.
I solved my problem via jQuery. Maybe someone needs this solution or knows something more beautiful.
In client template of SaleDateTime columnt I wrote:
columns.Bound(x => x.SaleDateTime).ClientTemplate("<input class='saleDateTimeEditor' id='SaleDateTime#=index(data)#' name='ImportedSalesList[#=index(data)#].SaleDateTime' value='#= ConvertedSaleDateTime #'>")
And in DataBound event of my kendo grid I initialized all kendo DateTimePickers:
$('.saleDateTimeEditor').each(function () {
var id = $(this).attr('id');
var value = new Date(Date.parse($(this).val()));
$("#" + id).kendoDateTimePicker({
value: value,
max: new Date(Date.now())
});
$('#'+id).attr('readonly', 'readonly');
});
ConvertedSaleDateTime is in format "yyyy/MM/dd hh:mm:ss"