Search code examples
javascriptc#jqueryajaxbootstrap-datepicker

Passing Value from Bootstrap Datepicker to C# Datetimeoffset Nullable type using javascript / jQuery


I have a Bootstrap datepicker in my View. I have set one of my model variable to public DateTimeOffset? expiryDate { get; set; } The Expiry date is an Optional field .So it's the User who uses the application decides whether to set an expiry date or not during a process. by using $('#datepickerid').val() i can get the current value from Datepicker and i need to send it to the controller via an ajax call. I use var expirydate = $("#datepickerid").val(); can i use this value via the ajax call ?


Solution

  • Yes, you can use the `var expirydate = $("#datepickerid").val()' in ajax call.

    For demo (fiddle), I have created a property in Model as

    [DataType(DataType.Date)]
    public DateTimeOffset? ExpiryDate { get; set; }
    

    And rendered input as :

    @Html.EditorFor(model => model.ExpiryDate, new {@class="form-control"})
    

    on click of button press, following ajax call is made :

    $.ajax({
        url: '@Url.RouteUrl(new{ action="YourAction", controller="YourController"})',
        data: {datetimeOffset: $('#ExpiryDate').val()},     type: 'POST',                                   success: function(resp) {
        <<Your code>>
    }});
    

    I have created this dotnet fiddle to demonstrate your ask. Please have a look into it.