Today’s article I will show you how you can create a datetime calendar without using jQuery in you asp.net core 8 mvc (mvc 6 and mvc 7) application in razor page and get the selected datetime at controller end and display in your view using c#.net(.cshtml, .vbhtml).
You may also like
Asp Net Core 8: Calendar Control Without Using jQuery In MVC
For displaying a datetime calendar in asp.net core mvc application first we need to create an asp.net core mvc application. Now add the controller and add a view. In this view add the below code.
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @Id = "formdata", @enctype = "multipart/form-data" }))
{
<div class="text-center">
<b>Select Date:</b>
@Html.TextBox("dataOfBirth", "", new { @class = "form-control", @type = "datetime-local" })
<br />
<input type="submit" value="Submit" />
<br /> <br />
<b>Your Selected Date: </b>@ViewBag.SelectedDate
</div>
}
In above code i have added a Form tag, TextBox control and a Submit button. Here in TextBox control our Calander control option will come to select the datetime. Ones you select the datetime in the textbox to get the selected date at controller end we need to click on Submit button.
In above code form tag with form method of post type (FormMethod.Post), This form tag will help us to post the form on click on submit button control. Here in TextBox control, name of the control is dataOfBirth. So, to make the textbox control have the datetime calendar control I have added a tag named as @type="datetime-local".
This attribute help to convert the textbox control into a datetime calendar control. In this I have used viewbag to display the selected value in calendar.
How To Add Calander Control in .cshtml File?
Now in Textbox control I have used an attribute @type = "datetime-local". This attribute help to convert the textbox control into a calendar control. In this I have used viewbag to display the selected value in calendar.
How to Add Post Method and Capture Value at Controller End?
To capture the selected value at controller end we need the passed parameter value in HttpPost method same as the control name in your view.
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(DateTime dataOfBirth)
{
var selectedDate = dataOfBirth;
ViewBag.SelectedDate = selectedDate;
return View();
}
In above code I am having HttpGet and HttpPost method. In post method we have a parameter with name dataOfBirth. So we are going the use this variable to get the selected date at controller end. Here one thing we need to notice one thing that the TextBox control name and the HttpPost method passed parameter is having the same name. To display the selected at view end we are passing or assigning the value to viewbag to display it on user end.
Now run the code and check the output.
Now click on Calendar icon. Your Calendar will open.