Passing a datepicker value from a C# MVC view to the controller

When a user selects a new date in my view, the default value is passed back to the controller instead of the newly selected one.

Controller:

public ActionResult ManualLoad(string source, string datepicker1)
{
    List<string> loadMessages = new List<string>();
    try
    {
        Lib.RunDate = datepicker1;
        loadMessages = Lib.AutoLoad(source);
    }
    catch (Exception e)
    {
        string errMsg = e.Message + ((e.InnerException == null) ? "" : e.InnerException.Message);
        ViewBag.ErrorMessage = errMsg;
    }

    return View(loadMessages);
}

View:

@{
    ViewBag.Title = "Loan Records";
    var date1 = String.Format("{0:yyyy-MM-dd}", String.IsNullOrEmpty(ViewBag.date1) ? DateTime.Today : ViewBag.date1);

    string warnMsg = "<div class=\"badge alert-danger btn-lg\">" + ProjectFunctions.getAdministratorWarnings() + "</div>";
}

    <p style="margin: 20px 20px 20px 20px">
        <label for="datepicker1">Enter Specific Run Date:</label>
        <input type="text" id="datepicker1" name="datepicker1" style="width:90px">
    </p>

  <p style="margin: 20px 20px 20px 20px">
      @Html.RouteLink("Select file for Manual LOAD for " + Lib.SOURCE_1, new { controller = "FTP", action = "ManualLoad", source = Lib.SOURCE_1, datepicker1 = date1, autoload = true })
      <span>
          Load and Process a new dataset (loan tape and loan docs) in one selection.
          <br />[ Retrieves loan tape files from: @Html.Raw(ProjectFunctions.getSourceDirectory(Lib.SOURCE_1, true)) ]
          <br />[ Retrieves loan docs from: @Html.Raw(ProjectFunctions.getLoanDocsRetrieveDirectory(Lib.SOURCE_1, true)) ]
          <br />[ Working Copies to: @Html.Raw(ProjectFunctions.getLoanDocsLoadDirectory(Lib.SOURCE_1)) ]
      </span>
  </p>

<p>@Html.RouteLink("Return to Administrative Tasks", new { controller = "Admin", action = "Index" })</p>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryui")

    <script type="text/javascript">
        $().ready(function() {
            $("#datepicker1").datepicker({
                showButtonPanel: true,
                minDate: new Date(2020, 1, 1),
                maxDate: new Date(),
                dateFormat: "yy-mm-dd"
            });

            $("#datepicker1").val('@date1');

        });

    </script>
}

Answer №1

The reason for the discrepancy is due to variations in date formats;

 var date1 = String.Format("{0:yyyy-MM-dd}", String.IsNullOrEmpty(ViewBag.date1) ? DateTime.Today : ViewBag.date1);

To resolve this issue, ensure consistency in date formats within your JavaScript:

dateFormat: "yyyy-MM-dd" 

Additionally, make sure to convert the date correctly in your action method:

Lib.RunDate = DateTime.ParseExact(datepicker1, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing selenium to interact with JavaScript-generated radio buttons

My Java code includes a set of dynamically generated radio buttons using JavaScript that I am trying to interact with. Despite attempting to use xpath to locate and click on one of the radio buttons, I keep receiving an error message: Exception in thre ...

Load components dynamically based on list of identifiers

With over 100 components at my disposal, not all of them will be needed on a single page. For instance, a user might select a list of component IDs (components_ids - [7, 50, 22]). When the page is visited, I will only load the components with IDs that ...

Adding a Javascript function dynamically and calling it in real-time

After a click event on the page, I use ajax to retrieve a block of html and script. Although I can successfully append the script element to the head element, WebKit based browsers are not recognizing it as a script (meaning I am unable to call a function ...

Differences between FindAll and Predicate<TSource> versus Func<TSource, bool>

I'm having trouble understanding why the method List<T>FindAll(...) doesn't accept Func<TSource, bool>, but instead requires Predicate<TSource>. For example, when I have a List of books and I only want to retrieve books that ar ...

Automatically initiate a click event when the page is loaded

I'm having trouble getting a click event to trigger on my controller when the page loads. I really just want the checkboxes to be clicked automatically. <!DOCTYPE html> <html > <head> <link rel="stylesheet" type="text/css" ...

JavaScript script to modify the parameter 'top' upon clicking

Here is the pen I've made. HTML <div class = 'cc'> <div class = 'bb'><div class = 'aa'> Some word </div></div> </div> CSS .cc { width: 100%; min-height: 90px; margin: 0; ...

Utilize the reference of a prop within a callback

I'm facing an issue where I am unable to reference the vue props within a callback in vue-chartjs. Whenever I try to access 'this', it gives me an 'undefined' error in the console log. Can someone please advise on the correct way t ...

Tips for updating the chosen value with jquery or javascript

I am facing a situation where I need to change the selected option in a dropdown menu using a function triggered onClick later in the application. <select id="myselect"> <option value=aa>aa</option> <option value=bb>bb</option&g ...

Get alerts from Twitter pushed to my site

Is it possible to create a web application that utilizes JavaScript to receive notifications from Twitter? I want my website app to send me notifications whenever a person I follow posts a new article. I'm having difficulty with this task and would gr ...

Retrieve data using ServiceStack from a multipart/form-data file

Currently, I'm facing a challenge in my project where I'm submitting a form with multipart/form-data from a React application to a .NET backend. In order to post the data using axios on the React side, I make use of FormData. When it comes to pro ...

Triggering AJAX call from several buttons within a single page in Django

Hey there! I'm currently working on implementing a voting feature using Ajax in my Django-based website. The issue I'm facing is that users can only vote on the first entry, but I want them to be able to vote on all entries. Can you assist me wit ...

TypeScript/Javascript - Error: The specified function is not callable

After recently delving into TypeScript, I found myself encountering an error in my code for a wheel mini-game on my app. The specific error being displayed in the console is: this.easeOut is not a function The relevant portion of the code causing the iss ...

React router-dom doesn't function properly when embedded in a nested organization

I am working on creating an authentication page with the following routes: /auth -> show auth status /auth/signin -> Sign in form /auth/signup -> Sign up form These are the components used in my App App.js function App() { return ( <Br ...

Personalized Cascading Selection Menu within the Django Administration Interface

I am struggling with implementing a dependent drop-down list within my Django admin page. I have a project foreign key in my Phase model and I would like the user to be able to select a project from the first drop-down, and then have the phases of that pro ...

The issue encountered when trying to load Javascript through PHP

As a beginner, please be patient with me. I am attempting to dynamically load this JavaScript easy slider into a div on my index page using the following code ... switch($_GET['page']) { case '#YELLOW' : $page = ' <div id ...

The comparison between installing a JavaScript library and simply copying .js files

As I dive into the world of web development and JavaScript, I've noticed that many open-source JavaScript libraries like jqueryUI come with readme files containing installation instructions. These instructions often mention the need to install additio ...

How can I identify the specific iframe that is invoking a JavaScript function within its parent?

Let's consider this scenario sample.html <script> function identifyCaller() { console.log(???); // what should be placed here to determine the caller? } <iframe src="frame1.html"></iframe> <iframe src="frame2.html"></if ...

Creating subarrays with identical strings from a given array: step-by-step guide

I currently have an array structured as follows : [ { "title": "name", "value": "" }, { "title": "version", "value": "" }, { "title": "inventory_name", "value": "" }, { "title": "inventory_version", "value": "" }, { "ti ...

The dropdownlists mysteriously vanish forever after a modal popup, likely due to a timer issue

We are encountering some unexpected behavior with dropdown lists on a relatively complex webpage when using IE6. The layout of the page consists of 2 update panels, each containing a GridView that displays data in a master-details format. Additionally, eac ...

I'm torn between sticking to my original code using pure JavaScript with jQuery AJAX calls or scrapping all client-side scripts and starting fresh by rewriting everything in .NET only

My website, built using jQuery and .NET/C#, is nearly complete - about 90% ready to be published. Taking a moment to reassess, I've come to the realization that my code isn't as secure as I thought. In fact, it's quite vulnerable due to some ...