简体   繁体   中英

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. 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

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. Currently the calendar shows 2 hardcoded available dates.

忙碌的猫

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? ie I need the calendar to show all the available dates in the database

Any help would be greatly appreciated!

My Datepicker model:

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:

@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(); in your controller. You'll need to adjust your view's Model declaration to match.

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. 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. 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. 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. 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

 [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

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.

Create a modol that containe the dates,and simple convert it to json

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

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