How can I attach an action event to a date picker in ASP.NET? - c#

I want to execute a method in the controller when I select a date. I have this:
<input class="form-control col-sm-5" asp-action="SetTimes" asp-for="Date" type="date" value="#DateTime.Today.ToString("dd-MM-yyyy")" />
The asp-action="SetTimes" was suggested by another student. I wanted it to call the method "SetTimes()" in the controller whenever I pick a date, but it doesn't work.

asp-action is invalid in the input datetype field. Instead, you can do this in the js onchange function.
<input class="form-control col-sm-5" onchange="SetTime(this.value)" asp-for="Date" type="date" value="#DateTime.Today.ToString("dd-MM-yyyy")" />
#section scripts{
<script>
function SetTime(value) {
window.location.href = "Controller/Action?Date=" + value;
}
</script>
}

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

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

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!

How to call an event handler when the value in a text box in an ASP.Net Razor Pages app is changed?

I'm building a web application using ASP.NET CORE 3.1. There is a data table(EvCode) that has two columns, EventCode (key field) and EventType. On the page that lets a user add a new event there are a number of fields. Among them is EventCode and EventType. When the EventCode is entered and the user exits the field, I want to trigger an event that queries the EvCode table using the the value in the EventCode field to select the EventType, then populate the the EventType field with the value.
If I add a button to the page, I can run the event handler. I need the event handler to run automatically when the value in the EventCode field is changed.
Any suggestions or ideas on how to do this are appreciated.
Fei Han - Thank you for your suggestions and code. I used a different project where I trying to accomplish the same thing. The only differences, rather than using EventCode I used FamilyCode, and rather than use EventType I used FamilyName. The handler (OnGetFamilyNameByCode) was never called.
I've included my code, maybe you can see what I've done wrong.`
<form method="get" >
<div class="border backgroundWhite">
<div class="form-group row">
<div class="col-2">
<label asp-for="PublisherFamilyVM.PubDataList.LastName"></label>
</div>
<div class="col-6">
<input asp-for="PublisherFamilyVM.PubDataList.LastName" class="form-control" />
</div>
<span asp-validation-for="PublisherFamilyVM.PubDataList.LastName" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="PublisherFamilyVM.PubDataList.FirstName"></label>
</div>
<div class="col-6">
<input asp-for="PublisherFamilyVM.PubDataList.FirstName" class="form-control" />
</div>
<span asp-validation-for="PublisherFamilyVM.PubDataList.FirstName" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
#Html.LabelFor(m => m.PublisherFamilyVM, "Family Code/Name:")
</div>
<div class="col-2">
<!-- <input asp-for="PublisherFamilyVM.PubDataList.FamilyCode" class="form-control" /> -->
<input id="input_family_code" class="form-control" type="text" value="" onblur="getfamilyname();" />
</div>
<div class="col-4">
<!-- <input asp-for="PublisherFamilyVM.FamilyList.FamilyName" class="form-control" /> -->
<input id="input_family_name" class="form-control" type="text" value="" />
</div>
<span asp-validation-for="PublisherFamilyVM.PubDataList.FamilyCode" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-6 offset-2">
<partial name="_CreateAndBackToListButton" />
</div>
</div>
</div>
</form>
#section Scripts{
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script>
function getfamilyname() {
var familycode = $("#input_family_code").val();
if (familycode != "") {
$.getJSON(`/eventinfo?handler=FamilyNameByCode&familycode=${familycode}`, function (data) {
//console.log(data);
$("#input_family_name").empty();
$("#input_family_name").val(data);
});
}
</script>
}
***** PageModel *****
public JsonResult OnGetFamilyNameByCode(string familycode)
{
//code logic here
//retrieve data from database based on famiycode
return new JsonResult(familycode);
}
When the EventCode is entered and the user exits the field, I want to trigger an event that queries the EvCode table using the the value in the EventCode field to select the EventType, then populate the the EventType field with the value.
To achieve above requirement, you can try to make AJAX request to handler method then dynamically populate value of EventType input field based on returned value in blur event of EventCode input field, like below.
<input id="input_event_code" type="text" value="" onblur="geteventtype();" />
<input id="input_event_type" type="text" value=""/>
JS code
function geteventtype() {
var eventcode = $("#input_event_code").val();
if (eventcode!="") {
$.getJSON(`/eventinfo?handler=EventTypeByCode&eventcode=${eventcode}`, function (data) {
//console.log(data);
$("#input_event_type").empty();
$("#input_event_type").val(data);
});
}
//...
}
handler method
public JsonResult OnGetEventTypeByCode(int eventcode)
{
//code logic here
//retrieve data from database based on eventcode
//...
return new JsonResult(eventtype);
}
Test Result
Update:
A 404 error does on the $.getJSON line of code indicating the url cannot be found. I replaced '/eventinfo?handler= FamilyNameByCode&familycode=${familycode}' - with - '/Create?handler = FamilyNameByCode&familycode=${familycode}' Do a need to add the folder or something else?
Please check if your Create model class look like below.
public class CreateModel : PageModel
{
//properties here
//...
public void OnGet()
{
}
public JsonResult OnGetFamilyNameByCode(int familycode)
{
//code logic here
//retrieve data from database based on eventcode
//...
return new JsonResult("FamilyName_Here");
}
}

How to call action from checkbox input using tag helpers

If I want to call controller action using input of type image I can do it like:
<form method="post">
<button asp-controller="Home" asp-action="Index">Click Me</button>
<input type="image" src="..." alt="Or Click Me" asp-controller="Home"
asp-action="Index">
</form>
Is it possible to do something similar with input of type checkbox using tag helpers like this:
<input type="checkbox" asp-for="#Model.Property" asp-controller="Home" asp-action="DoSomething" asp-route-propertyId="#Model.Id" class="form-control" />
? Or if I must write own custom tag helper for this?
Code below also does not work.
<input type="checkbox" asp-for="#Model.Property" onclick="#Url.Action("DoSomething", "Home", new { propertyId= Model.Id })" class="form-control" />
Edit:
Currentyly I found solution as follow:
<input type="checkbox" asp-for="#Model.Property" onclick="triggerLink(#Model.Property)" class="form-control" />
than I add following script:
function triggerLink(Property) {
var theUrl = '#Url.Action("DoSomething", "Home")?propertyId=' + Property;
window.location = theUrl;
}
It's working but I am still looking for a solution with tag helpers.

client side validation in htmlhelper without Model Class

I visited through different links but couldn't find desired answer. I am not using model for this view. Before sending data to server I want to check whether the text input is null or not.How can I validate it?
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<h2>Student Information</h2>
#using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
{
<label>First Name:</label>
<input type="text" class="form-control" name="firstname" id="f_name" />
<button type="submit" class="btn btn-success" >Insert</button>
}
</div>
<script>
$(function () {
$("#target".submit(function (event) {
event.preventDefault();
//return false;
})
})
</script>
Try this, I use empty string ('') instead of null since usually empty textbox are just empty string and not necessarily null.
<script>
$(function () {
$('button.btn').unbind();
$('button.btn').click(function () {
if($("#f_name").val() == ''){
return false;
}
return true;
})
})
</script>
If you dont want custom script for validating data on client side, you can use jquery.validate.js and jquery.validate.unobstrusive.js. This will work just like mvc validation rules(Actually this validation logic is generated by MVC itself on the view when client side validation is enabled).
Just add this three script file inside your page.
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js"></script>
Or you can select from your Script folder inside MVC application.
And Try to add following attribute in your Htmlelement for validation.
<div class="container">
<h2>Student Information</h2>
#using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
{
<label>First Name:</label>
<input data-val="true" data-val-required="First Name field is required." type="text" class="form-control" name="firstname" id="firstname" />
<span class="field-validation-valid" data-valmsg-for="firstname" data-valmsg-replace="true"></span>
<button type="submit" class="btn btn-success" >Insert</button>
}
</div>
This will work just like MVC validation inside your view.
You can get more information how to use JqueryValidate and jquery unobtrusive by clicking on this link : http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
You can get the value with a simple jQuery statement - $("#f_name").val() and then check if it is null $("#f_name").val() == null
So your complete javascript would be
<script>
$(function () {
$("#target".submit(function (event) {
event.preventDefault();
if($("#f_name").val() == null){
return false;
}
return true;
})
})
</script>

Categories

Resources