Date format change connected with ASP.NET Core 8 MVC with javascript

186 Views Asked by At

This is my HTML view:

<form method="post"
      asp-action="GetVillasByDate">
    <div class="row p-0 mx-0 py-4">

        <div class="col-12 col-md-5  offset-md-1 pl-2  pr-2 pr-md-0">
            <div class="form-group">
                <label>Check In Date</label>
                <input asp-for="CheckInDate" type="date" class="form-control" />
            </div>
        </div>

        <div class="col-8 col-md-3 pl-2 pr-2">
            <div class="form-group">
                <label>No. of nights</label>
                <select class="form-select" asp-for="Nights">
                    @for(var i = 1; i<11; i++)
                    {
                        <option value="@i">@i</option>
                    }
                </select>
            </div>
        </div>

        <div class="col-4 col-md-2 pt-4 pr-2">
            <div class="form-group">
                <button type="button" onclick="fnLoadVillaList()" class="btn btn-success btn-block">
                    <i class="bi bi-search"></i>  &nbsp; Check Availability
                </button>

            </div>
        </div>

    </div>
    <partial name="_VillaList" model="Model" />
</form>
@section scripts {
    <script>
        function fnLoadVillaList() {
            $('.spinner').show();
            var objData = {
                
                checkInDate: $("#CheckInDate").val(),
                nights: $("#Nights").val()
            };

            $.ajax({
                type: "POST",
                data: objData,
                url: "@Url.Action("GetVillasByDate", "Home")",
                success: function (data) {
                    $("#VillasList").empty();
                    $("#VillasList").html(data);
                    $('.spinner').hide();
                },
                failure: function (response) {
                    $('.spinner').hide();
                    alert(response.responseText);
                },
                error: function (response) {
                    $('.spinner').hide();
                    alert(response.responseText);
                }
            });
        }
    </script>
}

I used Visual Studio ASP.NET Core 8 MVC, and in my project I enter the date in input method and debug when the date changes to month. For example, debugging with the date 15.10.2023 shows the date 0001.01.01, and debugging with the date 5.6.2023 shows the date 6.5.2023. How to solve this?

1

There are 1 best solutions below

2
On

When dates are passed between client and server, they are usually in the form of strings. If the date string passed by the client does not conform to the date format expected by the server, the server may have problems when trying to parse it, causing the default value (0001-01-01 00:00:00) to be used. You need to ensure that the date string passed to the server is in a date format acceptable to the server. If the server uses a specific date format or time zone setting, the client should format the date string accordingly. By default, the browser provides a date format based on the user's operating system or browser settings, which results in a different format than the expected one. Inconsistent.

To ensure consistent date formatting, you can explicitly specify the date format instead of relying on the browser's default settings. You can use JavaScript to convert an input date to an ISO-formatted string. Make sure this date format is handled correctly on the server side.

function fnLoadVillaList() {
     $('.spinner').show();
     var rawDate = $("#CheckInDate").val();
     var nights = $("#Nights").val();

     var isoDate = new Date(rawDate).toISOString();
     var objData = {
         checkInDate: isoDate,
         nights: nights
     };

Updated:

[HttpPost]
    public IActionResult GetVillasByDate(DateTime checkInDate, int nights)
    {
            
        var villaList = new List<Villa>
    {
        new Villa { Id = 1, Name = "Luxury Villa 1", AvailableDate = new DateTime(2023, 12, 1) },
        new Villa { Id = 2, Name = "Beachfront Villa", AvailableDate = new DateTime(2023, 12, 5) },
        new Villa { Id = 3, Name = "Mountain View Villa", AvailableDate = new DateTime(2023, 12, 7) },
           
    };

        var availableVillas = villaList
            .Where(villa => villa.AvailableDate >= checkInDate && villa.AvailableDate <= checkInDate.AddDays(nights - 1))
            .ToList();

        return PartialView("_VillaList", availableVillas);
    }
}

Partial view:

@model List<Villa>

<div>
    <h3>Available Villas</h3>
    @if (Model != null && Model.Any())
    {
        <ul>
            @foreach (var villa in Model)
            {
                <li>@villa.Name - Available on: @villa.AvailableDate.ToShortDateString()</li>
            }
        </ul>
    }
    else
    {
        <p>No available villas found.</p>
    }
</div>

When I select the corresponding date: enter image description here

After i click the button: enter image description here