如何在MVC中添加jQuery Datepicker

来源:互联网 发布:java泛型使用 编辑:程序博客网 时间:2024/06/06 09:23

如何在MVC中添加jQuery Datepicker

 

1介绍

 

在本例中我们将叙述如何在一个MVC应用中添一个JQuery Datepicker(日期选择器)。 jQuery是广泛使用于网页开发的脚本语言之一, jQuery内置支持日期时间选择器,在本文中,我将解释如何在MVC日期时间选择器。

以下是步骤:

 

2步骤一

 

Visual Studio新建一个项目,选择 Web标签,再选择ASP.Net WebApplication,提供一个合适的项目名如DateTimeDemo,并单击Ok按钮。

1

3步骤二

 

在出现的下图中,选择MVC标签并单击OK按钮。

 

4步骤三

 

带有一些预定义控制器、脚本的项目解决方案已经被创建了,现在在Models文件夹添加一个名为Employee.cs 的类文件,该类带有三个自动实现的属性,如下:

 

public class Employee   

{   

    [Required]   

    [Display(Name = "Id")]   

    public int EmpId { get; set; }   

    [Display(Name = "Name")]   

    [Required]   

    public string EmpName { get; set; }   

    [Required]   

    [Display(Name = "Date Of Birth")]   

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]   

    public DateTime DOB { get; set; }   

}  

 

译注:类中添加如下引用:

using System;

using System.ComponentModel.DataAnnotations;

5步骤四

 

右击Controllers文件夹并选择控制选项,在将出现的下图所示的窗口中,选择 MVC5 Controller-Empty,为该控制器命名,如Employee,并单击添加按钮。

6步骤五

 

将自动产生如下所示的带有Index方法的控制器代码:

 

public class EmployeeController : Controller   

{   

    // GET: Employee   

    public ActionResult Index()   

    {   

        return View();   

    }   

}  

 

 

 

7步骤六

 

Index方法上任意地方右击鼠标,再单击添加视图,接着选择Employee模型类,Create类型模析,最后单击添加按钮,如下:

8步骤七

 

带有如下代码的Employee创建视图将被自动生成

 

 

@modeljquerydatepickerdemo.Models.Employee

 

@{

    ViewBag.Title ="Index";

}

 

<h2>Index</h2>

 

 

@using (Html.BeginForm())

{

    @Html.AntiForgeryToken()

    

    <div class="form-horizontal">

        <h4>Employee</h4>

        <hr />

        @Html.ValidationSummary(true,"",new { @class ="text-danger" })

        <div class="form-group">

            @Html.LabelFor(model => model.EmpId, htmlAttributes: new { @class ="control-label col-md-2" })

            <div class="col-md-10">

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

                @Html.ValidationMessageFor(model => model.EmpId, "",new { @class ="text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            @Html.LabelFor(model => model.EmpName, htmlAttributes: new { @class ="control-label col-md-2" })

            <div class="col-md-10">

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

                @Html.ValidationMessageFor(model => model.EmpName, "",new { @class ="text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            @Html.LabelFor(model => model.DOB, htmlAttributes: new { @class ="control-label col-md-2" })

            <div class="col-md-10">

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

                @Html.ValidationMessageFor(model => model.DOB, "",new { @class ="text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">

                <input type="submit" value="Create" class="btn btn-default" />

            </div>

        </div>

    </div>

}

 

<div>

    @Html.ActionLink("Back to List","Index")

</div>

 

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")

}

 

 将其中的                @Html.EditorFor(model => model.DOB, new { htmlAttributes =new { @class ="form-control" } })

 

改为:

                @Html.EditorFor(model => model.DOB, new { htmlAttributes =new { @class ="form-control", placeholder ="Employee Date Of Birth", @readonly ="true" } })

 

9步骤八

 

现在我们需要增加jQueryUi引用到项目中,缺省地,Visual Studio将不为我们 jQueryUI的引用,要jQueryUi引用,右击 References标签并选择Manage NuGet Packages,如下图所示:

10步骤九 

现在搜索 jQueryUI并选择安装来安装。

一旦jQueryUI引用被到你的项目,在Content scripts文件夹内会一些相关文件。

 

11步骤十

 

打开App_Start文件夹内的BundleConfig.cs.其中有一些缺省的代码,不要管它们,并在其后如下代码:

 

 

//Create bundel for jQueryUI   

//js   

bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(   

          "~/Scripts/jquery-ui-{version}.js"));   

//css   

bundles.Add(new StyleBundle("~/Content/cssjqryUi").Include(

                   "~/Content/themes/base/jquery-ui.css"));

  

译注:不同的jQueryUI的版本,需要打包的文件的目录可能有差别,需要根据实现情况进行改变。

 

 

 

 

上述代码将创建QueryUI的脚本包和CSS包,现在你只需要将这些包到你想使用 DatePicker的页面中。

 

12步骤十一

 

打开Index视图并将下述代码到视图的脚本区。

@section Scripts {   

  

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

@Styles.Render("~/Content/cssjqryUi")   

   

 <script type="text/javascript">   

     $(document).ready(function () {   

         $('input[type=datetime]').datepicker({   

             dateFormat: "dd/M/yy",   

             changeMonth: true,   

             changeYear: true,   

             yearRange: "-60:+0"   

         });   

   

     });   

</script>   

   

}  

 

译注:需要删除原来的@section Scripts {...}段。

 

 

13步骤十二

 

运行Index视图,你将得到如下图所示的日期选择器:

注意我在脚本中使用了以下代码:

dateFormat: "dd/M/yy",   

changeMonth: true,   

changeYear: true,   

yearRange: "-60:+0"  

 

 

 jQueryUI的自定义功能能使开发人员根据需要自定义日期选择器,详见  jQuery文档。

14总结

 

通过本教程使你理解如何添加一个日期选择器到MVC,下载示例代码可获得更好的理解,谢谢。我乐意从读者那儿获得反馈,请将您关于本文的反馈、问题或建议发送给我。

 

译注:对原文进行了少量的修改。

 

附:有时我们需要在列表窗口中设置开始日期和结束日期的筛选,在CSHTML文件中,以下列语句增加一个开始日期的选择器:

<div class="form-group">
            @Html.Label("开始日期", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type='datetime' name="startDate" class="form-control" />
            </div>
  </div>


当然,前述的jQueryUI的引入,打包,在页面中引入包等步骤不能缺少。

而是控制器端,我们可能通过类似如下的代码获得从页面传来的开始时间。

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(string searchString,string movieGenre,string startDate) {

            List<movies> _movies = new List<movies>();


            var Genrelst = new List<string>();
            string str = "SELECT distinct genre FROM movies ";
            DataTable dt = new MySqlBean().QuerytoDT(str);
            foreach (DataRow dr in dt.Rows) {
                Genrelst.Add(dr[0].ToString());
            }
            ViewBag.movieGenre = new SelectList(Genrelst);

            str = "select * from movies where id>-1 ";
            if (!String.IsNullOrEmpty(searchString)) str += " and title like '%" + searchString + "%' ";

            if (movieGenre.Length>0)
                str += " and genre='" + movieGenre + "' ";

            if (startDate.Lenght>0) str+="  and realedate>'"+startDate+"' ";

 

             dt = new MySqlBean().QuerytoDT(str);
            foreach (DataRow dr in dt.Rows) {
                movies movie = new movies();
                movie.id = Convert.ToInt32(dr[0].ToString());
                movie.title = dr[1].ToString();
                movie.genre = dr["genre"].ToString();
                movie.releasedate = Convert.ToDateTime(dr["releasedate"].ToString());
                movie.price = Convert.ToDecimal(dr["price"].ToString());
                _movies.Add(movie);
            }

 

            return View(_movies);
        }

 

 

 

 

 

0 0
原创粉丝点击