Kevin Schultz
Kevin Schultz

Reputation: 884

Get date value from date picker

I am very new to MVC and I am trying to get the date the user selects from the date picker and display another set of dates based on a user input. The date picker works fine however I am not sure how to get the value of the date and pass it to the calculation. I have created a textbox to get the number of days the user wants displayed and the button to initiate the calculation, however the way I created the button also created another text box.

Here is the view code:

@using (Html.BeginForm())
    {
        <h2>Enter The Number Of Days To Display</h2>
        Date: <input type="text" id="date" name="date"value ="Enter a number"/>
       @Html.TextBoxFor(model => model.DaysToBeViewed)
       <input type="submit" value="Display Days" />

Upvotes: 1

Views: 2127

Answers (2)

AmanVirdi
AmanVirdi

Reputation: 1685

  1. You can partially post the date value to the controller method. Like this:

    @using (Html.BeginForm()) {

    Enter The Number Of Days To Display

    Date: @Html.TextBoxFor(model => model.DaysToBeViewed) // change the type to button }

Javascript:

$(document).ready(function(){
   $("#submitDate").on("click", function(){
      $.ajax({
        type: "POST",
        url: "../MyController/Calculate?date=" + $("input#date").val(),
                                                           // syntax was wrong here
           success: function (result) {
              $("#DaysToBeViewed").val(result);
           },
           error: function () {
             alert("Error in calculation method");
           }
        });
       });
    });

Controller:

public string Calculate(string date) 
{
    // do your calculation here
    return date;
}
  1. If you want to post your data then you need to change your BeginForm somthing like this:

View:

@using (Html.BeginForm("Calculate", "ControllerName", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    <h2>Enter The Number Of Days To Display</h2>
        Date: <input type="text" id="date" name="date" value ="Enter a number"/>
       @Html.TextBoxFor(model => model.DaysToBeViewed)
       <input type="submit" value="Display Days" />
}

Model:

public class MyData
{
    public string DaysToBeViewed {get; set;}
    public string date {get; set;}
}

Controller:

[HttpPost]
public ActionResult Calculate(MyData myData) 
{
    // do your calculation here
    return View();
}

Upvotes: 2

afpinto
afpinto

Reputation: 101

have you tried with getDate?

var currentDate = $( "input#date" ).datepicker( "getDate" );

this returns the current date for the datepicker or null if no date has been selected.

You can check the API to see other alternatives (for example onSelect)

regards, André

Upvotes: 1

Related Questions