简体   繁体   English

从数据库列填充列表

[英]Populating a List from a Database column

I am currently working on an asp.net mvc project which allows users to select only available dates from a calendar in order to book a specific service. 我目前正在研究一个asp.net mvc项目,该项目允许用户从日历中仅选择可用日期以预订特定服务。 I currently have a Datepicker.cs model which holds a DateTime Date field and an int Id field and I have a DbContext class which I use to persist and retrieve this data 我目前有一个Datepicker.cs模型,该模型包含一个DateTime日期字段和一个int Id字段,并且我有一个DbContext类,用于持久化和检索此数据

namespace Calendar.Models
{
  public class CalendarDb : DbContext
  {
    public DbSet<Datepicker> Dates { get; set; }
  }
}

I am using jQuery UI Datepicker on my Create.cshtml page to show the available dates to users. 我在Create.cshtml页面上使用jQuery UI Datepicker向用户显示可用日期。 Currently the calendar shows 2 hardcoded available dates. 当前,日历显示2个硬编码的可用日期。

忙碌的猫

Now my question is, is it possible in the asp.net mvc framework to populate this hardcoded array (or even a list etc.) with all of the dates in the Date column in the Datepickers Db? 现在我的问题是,是否有可能在asp.net mvc框架中用Datepickers Db的Date列中的所有日期填充此硬编码数组(甚至列表等)? ie I need the calendar to show all the available dates in the database 即我需要日历以显示数据库中所有可用的日期

Any help would be greatly appreciated! 任何帮助将不胜感激!

My Datepicker model: 我的Datepicker模型:

namespace Calendar.Models
{
  public class Datepicker
  {
    public DateTime DtmDate { get; set; }
    public int Id { get; set; }
    public int UserId { get; set; }
  }
}

Controller for the view: 视图的控制器:

    [HttpGet]
    public ActionResult Create()
    {
       var model = _db.Dates.ToList();
       return View(model);
    }

My Create.cshtml view as it stands: 我的Create.cshtml视图如下:

@model Calendar.Models.Datepicker

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
    <h4>Datepicker</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.DtmDate, htmlAttributes: new { @class 
= "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DtmDate, new { htmlAttributes = 
new { @class = "form-control1" } })
            @Html.ValidationMessageFor(model => model.DtmDate, "", new { 
@class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.UserId, htmlAttributes: new { @class = 
"control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserId, new { htmlAttributes = 
new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.UserId, "", 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>

<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />

@section scripts {
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script>
    jQuery(function(){
        var enableDays = ["11-07-2019", "12-07-2019"];

        function enableAllTheseDays(date) {
            var sdate = $.datepicker.formatDate('dd-mm-yy', date)
            console.log(sdate)
            if ($.inArray(sdate, enableDays) != -1) {
                return [true];
            }
            return [false];
        }

        $(".form-control1").datepicker({
            dateFormat: "dd/MM/yy",
            beforeShowDay: enableAllTheseDays

        });
    });

</script>

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

<style>
.my-class a {
     background-color: #07ea69 !important;
     background-image :none !important;
     color: #ffffff !important;
}
</style>

Your model type is a List, because of the line var model = _db.Dates.ToList(); 由于行var model = _db.Dates.ToList();因此您的模型类型为List var model = _db.Dates.ToList(); in your controller. 在您的控制器中。 You'll need to adjust your view's Model declaration to match. 您需要调整视图的Model声明以使其匹配。

Change 更改

@model Calendar.Models.Datepicker

to

@model List<Calendar.Models.Datepicker>

Now that your model is of the correct type, you can embed the dates into your JavaScript. 现在您的模型类型正确,您可以将日期嵌入到JavaScript中。 We need to select the dates using Linq, and convert them to the proper string format that the JS is expecting, and then use some string methods to concatenate them together. 我们需要使用Linq选择日期,并将其转换为JS期望的正确字符串格式,然后使用一些字符串方法将它们连接在一起。 Change this: 更改此:

var enableDays = ["11-07-2019", "12-07-2019"];

to

var enableDays = [' @Html.Raw(string.Join("','", Model.Select(d => d.DtmDate.ToString("MM-dd-yyyy"))) '];

Then run it all. 然后全部运行。 In the rendered HTML, you should see the dates from your database nicely embedded in the JavaScript, which should enable the correct days in your datepicker. 在呈现的HTML中,您应该看到很好地嵌入到JavaScript中的数据库中的日期,这应该在datepicker中启用正确的日期。 Obviously you'll need to deal with edge cases, such as there being no rows in your table, or the date being null in one of the rows. 显然,您需要处理一些极端情况,例如表中没有行,或者其中一行中的日期为null。 But that should get you started. 但这应该可以帮助您入门。

Here is an idee of how you could do it. 这是您如何做的一个想法。

First create a method that return a List<DateTime> example 首先创建一个返回List<DateTime>示例的方法

 [HttpPost]
    public ActionResult GetDates()
    {

        return Json(CalendarDb.Dates.Select(x=> x.DtmDate.ToString("dd-MM-yyyy")));
    }

Now when you create your datepickider you will need this list eg enableDays 现在,当您创建日期选择器时,您将需要此列表,例如enableDays

var enableDays = [];
 $.ajax({
  url: "/GetDates",
  method: "POST" ,// post or get
  async: false,
  success:function(dates){ enableDays =dates; }
});

// now create your DatePicker.

Now if you want an mvc modol solution you could do it like this. 现在,如果您要使用mvc modol解决方案,可以这样做。

Create a modol that containe the dates,and simple convert it to json 创建一个包含日期的modol,然后简单地将其转换为json

enableDays  =@Html.Raw(Json.Encode(modol.Dates.ToString("dd-MM-yyyy")))
// now create your DatePicker.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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