ASP.NET Core HTML Helper is not setting Default Value for Date - c#

I have a form where I want the date to default to today's date.
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<input asp-for="ThrDate" class="form-control" value="#DateTime.Now"
type="date" asp-format="{0:yyyy-MM-dd HH:mm}" />
<span asp-validation-for="ThrDate" class="text-danger"></span>
</div>
My research would suggest that this would work, but the value is not actually passing through. Oh, and I still want the date picker to work.
Thanks!

You can try the following code:
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<input asp-for="ThrDate" class="form-control" id="date_info" type="date" asp-format="{0:yyyy-MM-dd}" />
<span asp-validation-for="ThrDate" class="text-danger"></span>
</div>
#section Scripts{
<script>
$(document).ready(function () {
var time = new Date();
var day = ("0" + time.getDate()).slice(-2);
var month = ("0" + (time.getMonth() + 1)).slice(-2);
var today = time.getFullYear() + "-" + (month) + "-" + (day);
$('#date_info').val(today);
})
</script>
}
Result:
And if you want use datetimepicker,you can use following code:
<div class="form-group">
<label asp-for="ThrDate" class="control-label"></label>
<div class="input-group date" id="datetimepicker1" data-target-input="nearest">
<input class="form-control datetimepicker-input" asp-for="ThrDate" type="text" 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>
#section Scripts{
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.1/js/tempusdominus-bootstrap-4.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.1/css/tempusdominus-bootstrap-4.min.css" />
<script>
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY HH:mm',
defaultDate: new Date(),
});
</script>
}
Result:

And another post gives us the answer:
Set default input value Datetime.Now on create view MVC ASP.NET Core 2?
but it's in the comments, so I will detail here.
In the controller, in the GET, set the value of the model item, such like:
PostThr postThr = new PostThr { ThrDate = DateTime.Now };
return view(model);
once you do this, the value assigned in the controller passes to the view. No modification to the view is necessary.
Side note: I seem to now have trouble with the formatting of the value, but that's rich world problems, or another question.
Shout out to Stephen Muecke!

Related

How to set input type date's default value to today?using ASP net core 7.0

<input type="date" id="ngaydk" value="01/02/2023">
<input type="date" id="ngaydk" value="01/02/2023">
or
ViewData["greeting2"] = "01/01/2023";
<input type="date" class="form-control" id="ngaydk" value=#ViewData["greeting2"]>
resual :
I want show value "01/02/2023" at load page but
not show value "01/02/2023" helpme!
Format for a date value is YYYY-MM-DD
<input type="date" value="2023-02-01">
I have an asp.net core web application and this is what I have in my index.cshtml
<div>
<label>date:</label>
<input type="date" id="ngaydk" />
<input type="date" id="ngaydk2" />
<input type="date" id="mydate" />
#Html.TextBox("date1", DateTime.Now.ToString("yyyy-MM-dd"), new { type = "date" })
</div>
<script>
document.getElementById("mydate").valueAsDate = new Date();
console.info(document.getElementById("mydate").value);
</script>
#section Scripts{
<script>
$(function () {
console.info("value is :" + $("#ngaydk2").val());
$("#ngaydk2").val('#DateTime.Now.ToString("yyyy-MM-dd")');
console.info("value is :" + $("#ngaydk2").val());
});
</script>
}

Create a Condition For all non empty fields to be ReandOnly - ASP.NET Core 6.0 MVC

I am developing my first web application with ASP.NET Core 6, and I have a form that shows some fields that I already have information inside of my database.
The problem is: these fields needs to be read-only, because my user needs to considerate the information from my database. If is null, then he needs to insert a value.
Here is an example (consider the field with already set readonly). Most of fields will need this code:
<div class="form-group row">
<div class="col-3">
<label for="Renda Bruta">Associado Desde:</label>
<input type="text" class="form-control">
</div>
<div class="col-3">
<label for="Renda Liquida">Cota Capital</label>
<input type="text" class="form-control">
</div>
<div class="col-6" style="text-align:center">
<label for="ServidorPublico">IAP:</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Quantidade" value="#Html.DisplayFor(model => model.iAP.QuantidadeProduto)" ReadOnly="readonly"/>
<input type="text" class="form-control" placeholder="Produtos" value=""#Html.DisplayFor(model => model.iAP.Pro)" ReadOnly="readonly"/>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label for="Renda Bruta">Margem Contribuição</label>
<input type="text" class="form-control">
</div>
<div class="col-8" style="text-align:center">
<label for="ServidorPublico">Cheque Especial</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Dias de Utilização" />
<input type="text" class="form-control" placeholder="Valor Utilizado" />
<input type="text" class="form-control" placeholder="Valor Contratado" />
</div>
</div>
</div>
I already build the form, and put some fields readonly with ReadOnly="readonly", but is there a way to loop all fields and put readonly with a loop or I really need to write in all fields the code `ReadOnly="readonly" ? My form is really big
But is there a way to loop all fields and put readonly with a loop or
I really need to write in all fields the code `ReadOnly="readonly" ?
My form is really big
Yes, you can set that ReadOnly attribute based on the value of your textbox field.
In this scenario you have to consider two way, either you should consider your textbox name attribute or type="text" attribute. Upon these two very way we will be decided which textbox set to readonly which is not.
For [type='text'] Attribute:
When [type='text'] means we will check all the textbox type of text and check if the textbox have value and set the readonly attribute:
View:
<div class="form-group row">
<div class="col-3">
<label for="Renda Bruta">Associado Desde:</label>
<input type="text" name="Associado" class="form-control">
</div>
<div class="col-3">
<label for="Renda Liquida">Cota Capital</label>
<input type="text" name="Cota" class="form-control">
</div>
<div class="col-6" style="text-align:center">
<label for="ServidorPublico">IAP:</label>
<div class="input-group mb-3">
<input type="text" name="Quantidade" class="form-control" placeholder="Quantidade" value="Test Value" />
<input type="text" name="Produtos" class="form-control" placeholder="Produtos" value="Test Value Products" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label for="Renda Bruta">Margem Contribuição</label>
<input type="text" name="Margem" class="form-control">
</div>
<div class="col-8" style="text-align:center">
<label for="ServidorPublico">Cheque Especial</label>
<div class="input-group mb-3">
<input type="text" name="Dias" class="form-control" placeholder="Dias de Utilização" />
<input type="text" name="Utili" class="form-control" placeholder="Valor Utilizado" />
<input type="text" name="Contra" class="form-control" placeholder="Valor Contratado" />
</div>
</div>
</div>
Script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("input[type='text']").each(function (index, item) {
console.log(item);
if ($(item).val() != "") {
$(item).attr('readonly', true);
}
});
});
</script>
}
Note: When will will set readonly to a textbox which has value based on the text type then we have to consider like input[type='text']
For name Attribute:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("input").each(function (index, item) {
console.log(item);
if ($(item).val() != "") {
$(item).attr('readonly', true);
}
});
});
</script>
}
Note: Remember in this scenario, you need to set name property for your textbox to identify uniquely as you can see I have added name property
Output:
what I understand that you want to make the input field enterable when the value of it is null. this is done by javascript.
I suggest to make all input fields read only.
use javascript to test each field, if its value is null make it enterable.
for example:
<input type="text" id="text1" class="form-control" placeholder="Quantidade" value="#Html.DisplayFor(model => model.iAP.QuantidadeProduto)" ReadOnly="readonly"/>
<script>
window.onload = function() {
if (document.getElementById("text1").value.length == 0)
{
document.getElementById("text1").readOnly = false;
}}
</script>
so basically when the page is loading the script will check if the input is null or not and it will do the action.

Bootstrap DateTimePicker not showing calendar when clicked

recently I tried to use Bootstrap DateTimePicker in my ASP.NET MVC project, and the calendar just wont show up. I believe I already put the Scripts and CSS in the right order.
Here is my CSS and Scripts :
<link href="~/Content/css/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/moment.min.js" type="text/javascript"></script>
<script src="~/Scripts/bootstrap.min.js" type="text/javascript"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js" type="text/javascript"></script>
#RenderSection("Scripts", required: false)
And this is my View Page :
<div class="col-md-3">
<div class="form-group">
<label>Tanggal Survey </label>
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({
format: 'DD MMMM YYYY'
});
});
</script>
}
And when I click the input, it just show the date and never show the pop-up calendar,
here is the example
Check the examples here: minimum setup
For your datepicked to open with clicking on the input you need to remove the glyph and go with the minimum setup.
<div class="container">
<div class="row">
<div class='col-sm-6'>
<input type='text' class="form-control" id='datetimepicker4' />
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker4').datetimepicker();
});
</script>
</div>
</div>
Otherwise you can do this:
$(function() {
$('.datetimepicker').datetimepicker();
$('.datetimepicker-addon').on('click', function() {
$(this).prev('input.datetimepicker').data('DateTimePicker').toggle();
});
});

Using DatePicker with .NET

I have created a very simple DatePicker using .NET Core. Here is my model:
public class MemberViewModel
{
public string Name { get; set; }
[DisplayFormat(DataFormatString = #"{0:dd\/MM\/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DOB { get; set; }
}
Here is my View:
#model DatePicker.Models.MemberViewModel
#{
ViewData["Title"] = "MemberView";
}
<h2>MemberView</h2>
<h4>MemberViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="MemberView">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DOB" class="control-label"></label>
#Html.TextBox("datepicker")
#*<input asp-for="DOB" class="form-control" />
<span asp-validation-for="DOB" class="text-danger"></span>*#
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Here is my Layout:
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Restrict date range</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker({ minDate: -20, maxDate: "+1M +10D", dateFormat: "dd/mm/yy" });
});
</script>
The DatePicker does nothing when I click on the textbox (in all browsers). The strange thing is; if I copy and paste the HTML generated into a HTML file and then double click on the HTML file, then the DatePicker works as expected. What is the problem?
Update
Please see the HTML generated below:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Restrict date range</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker({ minDate: -20, maxDate: "+1M +10D", dateFormat: "dd/mm/yy" });
});
</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MemberView - DatePicker Hotla</title>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">DatePicker</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
</nav>
<div class="container body-content">
<h2>MemberView</h2>
<h4>MemberViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form action="/Home/MemberView" method="post">
<div class="form-group">
<label class="control-label" for="Name">Name</label>
<input class="form-control" type="text" id="Name" name="Name" value="" />
<span class="text-danger field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label class="control-label" for="DOB">DOB1</label>
<input id="datepicker" name="datepicker" type="text" value="" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8AZxPMp7tE9EgVGFaTl7fvF-ALxvEVCrHkYj_isQTt5HUG2iu3EPMhNjR_6OlI2xtybr9grj4e4c3eFwe5jY-8r5YWeWIdtSNkc5IsvYnt9JYc5ftpPSzAqzINzih1yg85DFHJLEkWRZ2EjvupuQQ5E" /></form>
</div>
</div>
<div>
Back to List
</div>
<hr />
<footer>
<p>© 2018 - DatePicker</p>
</footer>
</div>
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/site.js?v=4q1jwFhaPaZgr8WAUSrux6hAuh0XDg9kPS3xIVq36I0"></script>
<script src="/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</body>
</html>
If I comment out the following line, then it works as expected:
<script src="/lib/jquery/dist/jquery.js"></script>
You are including jQuery twice. The second jQuery inclusion overwrites your $ variable, removing the jQuery ui plugins you loaded beforehand.
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
and
<script src="/lib/jquery/dist/jquery.js"></script>
jQuery plugins work by extending the $ variable. You second inclusion of jQuery destroys the plugins previously loaded.

Trying to implement bootstrap datepicker to my ASP.NET MVC website

I have the following calls in my View that should let me open the Calendar and select a date, I'm not sure I understand how to implement Datepicker.
<script>
$(document).ready(function () {
$(".datepicker").datepicker();
});
</script>
<li class="input-group-addon">
<label><%= CRAWebSiteMVC.Properties.Resources.EndDate %> :</label>
<input type="text" class="datepicker" placeholder="Click me!">
</li>
I have installed bootstrap datepicker on the NuGet, what am I missing or not understanding?
Use this for initizalis your Datepicker:
<script type="text/javascript">
$(function () {
$('#date').datepicker({
format: 'dd.mm.yyyy',
weekStart: 1,
clearBtn: true,
language: 'de-DE',
autoclose: true,
forceParse: false,
calendarWeeks: true
});
});
</script>
<li class="input-group-addon">
<label><%= CRAWebSiteMVC.Properties.Resources.EndDate %> :</label>
<input id="date" type="text" class="datepicker" placeholder="Click me!">
</li>
For more formatting see bootstrap-datepicker sandbox you will also find an example of the implementation
this is how you implement bootstrap datepicker in html page link
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker();
});
</script>
</div>
</div>
how to test if bootstrap 3 is loaded or not link
// Will be true if bootstrap 3 is loaded, false if bootstrap 2 or no bootstrap
var bootstrap3_enabled = (typeof $().emulateTransitionEnd == 'function');

Categories

Resources