从cshtml文件中检索日期选择器中的值到应用程序

本文关键字:应用程序 选择器 日期 cshtml 文件 检索 | 更新日期: 2023-09-27 17:59:47

我是"MVC"的新手,一直在尝试使用"Jquery"日期选择器"从用户那里获取日期并将其检索回主应用程序,请给我一些将日期检索回应用程序(控制器)的指导。以下是我的代码:

搜索.cshtml

@model Dropdowns.Models.SearchModel
@{ ViewBag.Title = "Search RedSea"; }
<head>
    <title>RedSea holidays</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css">
    <!-- Code to wire up your DatePicker -->
    <script type="text/javascript">
        $(function () {
            // This will make every element with the class "date-picker" into a DatePicker element
            $('.date-picker').datepicker(); //Date Picker script
        })
    </script>
    <script type="text/javascript">
    </script>


</head>
<div class="row">
    <div class="col-sm-4 col-sm-offset-4">
        <h1>Search Red-Sea Holidays</h1>
        <div class="panel panel-default">
            <div class="panel-body">
                @using (Html.BeginForm("Search", "Search", FormMethod.Post, new { role = "form" }))
                {

                    @* State selection dropdown *@
                    <div class="form-group">
                        @Html.LabelFor(m => m.Airport)
                        @Html.DropDownListFor(m => m.Airport, 
                        Model.Airports,
                        "- Please select a Airport -",
                        new { @class = "form-control" })
                    </div>
                    @* Destination Dropdown*@
                    <div class="form-group">
                        @Html.LabelFor(m => m.Destination)
                        @Html.DropDownListFor(m => m.Destination,
                     Model.Destinations,
                       "- Please select a Destination -",
                       new {@class = "form-control"})
                    </div>
                    @* Preferred Accomodation Dropdown *@
                    <div class="form-group">
                     @Html.LabelFor(m => m.PreferredAccomodation)
                     @Html.DropDownListFor(m => m.PreferredAccomodation,
                         Model.PreferredAccomodations,
                       "- Please select Preferred Accomodation -",
                       new {@class = "form-control"})
                    </div>
                    <label>Desired Departure Date</label>
                    <input class="date-picker" /> //date picker control
                    <div class="form-group">
                     @Html.LabelFor(m => m.Duration)
                        @Html.DropDownListFor(m => m.Duration,
                       Model.Durations,
                       "- Please select Preferred Number of Rooms-",
                       new { @class = "form-control" })
                    </div>
                    <div class="form-group">
                     @Html.LabelFor(m => m.Room)
                     @Html.DropDownListFor(m => m.Room,
                         Model.Rooms,
                       "- Please select Preferred Number of Rooms-",
                       new { @class = "form-control" })
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>                    
                }
            </div>
        </div>
    </div>
</div>

SearchController.cs

using System.Collections.Generic;
using System.Web.Mvc;
using Dropdowns.Models;
using System;
namespace Dropdowns.Controllers
{
    public class SearchController : Controller
    {
        //
        // 1. Action method for displaying 'Sign Up' page
        //
        public ActionResult Search()
        {
            // Let's get all states that we need for a DropDownList
            var Airports = GetAllAirports();
            var Destinations = getAllDestinations();
            var PreferredAccomodations = getAllAccomodations();
            var Durations = getAllDurations();
            var Rooms = getAllRooms();
            var model = new SearchModel();

            // Create a list of SelectListItems so these can be rendered on the page
            model.Airports = GetSelectListItems(Airports);
            model.Destinations = GetSelectListItems(Destinations);
            model.PreferredAccomodations = GetSelectListItems(PreferredAccomodations);
            model.Durations = GetSelectListItems(Durations);
            model.Rooms = GetSelectListItems(Rooms);
            return View(model);
        }
        //
        // 2. Action method for handling user-entered data when 'Sign Up' button is pressed.
        //
        [HttpPost]
        public ActionResult Search(SearchModel model)
        {
            // Get all states again
            var airports = GetAllAirports();
            var Destinations = getAllDestinations();
            var PreferredAccomodations = getAllAccomodations();
            var Durations = getAllDurations();
            var Rooms = getAllRooms();
            // Set these states on the model. We need to do this because
            // only the selected value from the DropDownList is posted back, not the whole
            // list of states
            model.Airports = GetSelectListItems(airports);
            model.Destinations = GetSelectListItems(Destinations);
            model.PreferredAccomodations = GetSelectListItems(PreferredAccomodations);
            model.Durations = GetSelectListItems(Durations);
            model.Rooms = GetSelectListItems(Rooms);
            // In case everything is fine - i.e. both "Name" and "State" are entered/selected,
            // redirect user to the "Done" page, and pass the user object along via Session
            if (ModelState.IsValid)
            {
                Session["SearchModel"] = model;
                return RedirectToAction("Done");
            }
            // Something is not right - so render the registration page again,
            // keeping the data user has entered by supplying the model.
            return View("Search", model);
        }
        //
        // 3. Action method for displaying 'Done' page
        //
        public ActionResult Done()
        {
            // Get Sign Up information from the session
            var model = Session["SearchModel"] as SearchModel;
            // Display Done.html page that shows Name and selected state.
            return View(model);
        }
  //      public DateTime getDatePickerValue()
 //       {
           // var dt = new DateTime(DateTime.Parse($('#FromDateCollected').val()));
           // alert(dt);
        //    return dt; 
  //      }
        // Just return a list of states - in a real-world application this would call
        // into data access layer to retrieve states from a database.
        private IEnumerable<string> GetAllAirports()
        {
            return new List<string>
            {
                "London Gatwick",
                "Manchester",
                "Birmingham",
                "Belfast",
                "Bristol",
                "Cardiff",
                "East Midlands",
                "Edinburgh",
                "Exeter",
                "Glasgow",
                "London Heathrow",
                "London Luton",
                "Newcastle",
                "London Stansted",
            };
        }
        private IEnumerable<string> getAllDestinations()
        {
            return new List<string>
            {
                "Egypt",
                "Sharm El Sheikh",
                "Hurghada",
                "Marsa Alam",
                "Luxor",
                "Tunisia",
                "Djerba",
                "Tunisia (Mainland)",
            };
        }
        private IEnumerable<string> getAllAccomodations()
        {
            return new List<string>
            {        
            "Red Sea Saver: 4 Sun, Sharm el Sheikh",
            "The Grand Hotel, Sharm el Sheikh",    
            "Hilton Sharm Waterfalls Resort",     
            "Xperience St George Homestay",       
            "Sharm Plaza Hotel",       
            "Sharm Resort Hotel",      
            "Ghazala Gardens Hotel",
            "Ghazala Beach Hotel",         
            "Hilton Sharm Dreams Resort",        
            "Hilton Fayrouz Resort",       
            "Mövenpick Resort",        
            "Baron Palms Resort",        
            "Siva Sharm Resort & Spa",         
            "Sierra Sharm el Sheikh Hotel",
            "Melia Sharm Resort &amp; Spa",        
            "Hilton Sharks Bay Resort",         
            "Xperience Sea Breeze Resort",       
            "Cleopatra Luxury Resort",         
            "Rixos Sharm el Sheikh Hotel",          
            "Park Inn Sharm el Sheikh Resort",          
            "Iberotel Il Mercato Hotel",          
            "Royal Albatros Moderna Hotel",         
            "Iberotel Dahabeya",         
            "Le Meridien Dahab Resort",        
            "The Makadi Spa Hotel",         
            "The Makadi Palace Hotel",         
            "The Grand Makadi Hotel",        
            "Sunwing Makadi Hotel",         
            "Fort Arabesque Resort",        
            "Cleopatra Luxury Resort, Makadi Bay",         
            "Siva Grand Beach Hotel",       
            "The Grand Resort, Hurghada",      
            "The Grand Hotel, Hurghada (B&amp;B)",       
            "The Grand Hotel, Hurghada (All Inclusive)",
            "Jungle Aqua Park Hotel",       
            "Red Sea Saver: 4 Sun, Hurghada",          
            "Red Sea Saver: 5 Sun, Makadi Bay",         
            "Movenpick Resort &amp; Spa El Gouna",       
            "Three Corners Rihana Resort",        
            "The Captain’s Inn", 
            "Sheraton Miramar Resort El Gouna",        
            "Mosaique Hotel",      
            "Fanadir Hotel",        
            "The Oberoi Hotel, Sahl Hasheesh",      
            "Tropitel Sahl Hasheesh Resort",     
            "Sheraton Soma Bay Resort",       
            "The Palace Port Ghalib Resort",        
            "Siva Port Ghalib Resort",         
            "Hilton Marsa Alam Nubian Resort",   
            "Fayrouz Plaza Beach Resort",        
            "Maritim Jolie Ville Kings Island Hotel",        
            "Iberotel Luxor Hotel",       
            "Sonesta St George Hotel",
           };
        }
        private IEnumerable<string> getAllDurations()
        {
            return new List<string>
            {
                    "7 nights",
                    "9 nights",
                    "10 nights",
                    "11 nights",
                    "12 nights",
                    "14 nights",
            };
        }
        private IEnumerable<string> getAllRooms()
        {
            return new List<string>
            {
                "1",
                "2",
                "3",
            };                
        }
        // This is one of the most important parts in the whole example.
        // This function takes a list of strings and returns a list of SelectListItem objects.
        // These objects are going to be used later in the SignUp.html template to render the
        // DropDownList.
        private IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
        {
            // Create an empty list to hold result of the operation
            var selectList = new List<SelectListItem>();
            // For each string in the 'elements' variable, create a new SelectListItem object
            // that has both its Value and Text properties set to a particular value.
            // This will result in MVC rendering each item as:
            //     <option value="State Name">State Name</option>
            foreach (var element in elements)
            {
                selectList.Add(new SelectListItem
                {
                    Value = element,
                    Text = element
                });
            }
            return selectList;
        }

}

    }

SearchModel.cs

using System.Collections.Generic;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System;
namespace Dropdowns.Models
{
    public class SearchModel
    {
        // This property will hold a state, selected by user
        [Required]
        [Display(Name = "Airport")]
        public string Airport { get; set; }
        // This property will hold all available states for selection
        public IEnumerable<SelectListItem> Airports { get; set; }
        [Required]
        [Display(Name = "Destination")]
        public string Destination { get; set; }
        public IEnumerable<SelectListItem> Destinations { get; set; }
        [Display(Name = "OutboundDate")]
        public DateTime OutboundDate {get; set;}
        [Required]
        [Display(Name = "PreferredAccomodation")]
        public string PreferredAccomodation { get; set; }
        public IEnumerable<SelectListItem> PreferredAccomodations { get; set; }
        [Required]
        [Display(Name = "Duration")]
        public string Duration { get; set; }
        public IEnumerable<SelectListItem> Durations { get; set; }

        [DataType(DataType.Date)]
        public DateTime DepatureDate { get; set; }
        [Required]
        [Display(Name = "Rooms")]
        public string Room { get; set; }
        public IEnumerable<SelectListItem> Rooms {get; set;}
    }
}

从cshtml文件中检索日期选择器中的值到应用程序

您需要将名称值对与您的输入元素(如)相关联

  <input class="date-picker" name="departureDate" />

然后您将选择该值。

在控制器的操作方法中,您需要一个名称与datapicker输入元素名称完全相同的输入参数,在这种情况下,它需要是"departureDate"

在您的视图中改为:

<input class="date-picker" /> //date picker control

这样做:

@Html.TextBoxFor(m => m.DepartureDate, new {@class = "date-picker"})

并在同一视图中添加以下javascript:

$('.date-picker').datepicker(); // you already have this line

现在,当您执行提交时,所选日期将绑定到模型中存档的DepartmentDate