简体   繁体   中英

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" />
  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();
}

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é

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM