简体   繁体   中英

What is the best and most efficient way to get data by JavaScript from EntityFramework database in my case?

Right now in my ASP.NET MVC Core2 project I have a model in EF database , that contains several properties:

public class SchoolEvents
    {
        public long ID { get; set; }
        [Required]
        [StringLength(40, ErrorMessage = "Max 40 characters")]
        public string Title { get; set; }
        [Required]
        public string Description { get; set; }
        [Required]
        public DateTime WhenHappens { get; set; }
    }

I have no problem to get data from the EF database by MVC Razor Views . But I am using JavaScript Calendar plugin in one of my Views, that will mark events from db on it. To do it, the script is taking data in format:

{ title: 'EventTitle', description: 'Few words about the event', datetime: new Date(2018, 8, 14, 16) }

It seems to be obvious, that I supposed to use a for loop in the script, iterating on db objects.

As I am still noob about JS , right now the only way I know to do it is:

-to create JSON file in the controller:

[Route("events")]
        [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
        public ActionResult Comments()
        {
            var _events= _context.Events.OrderBy(c => c.ProductID).ToList(); //yes, I know, I should use repository in the best practice
            return Json(_events);
        }

-in JS file I can use kinf of loadEventsFromServer() function, that uses XMLHttpRequest or Fetch and parsing it (I do not know yet how to do the parsing, I will be happy to get some suggestions),

And that it is it. Do you have some other ideas how to do it?

EDIT :

Update with part of plugins code, for console error d is undefined :

for (var i = 0; i < 42; i++) {
                var cDay = $('<div/>');
                if (i < dWeekDayOfMonthStart) {
                    cDay.addClass('c-day-previous-month c-pad-top');
                    cDay.html(dLastDayOfPreviousMonth++);
                } else if (day <= dLastDayOfMonth) {
                    cDay.addClass('c-day c-pad-top');
                    if (day == dDay && adMonth == dMonth && adYear == dYear) {
                        cDay.addClass('c-today');
                    }
                    for (var j = 0; j < settings.events.length; j++) {
                        var d = settings.events[j].datetime;
                        if (d.getDate() == day && d.getMonth() == dMonth && d.getFullYear() == dYear) {
                            cDay.addClass('c-event').attr('data-event-day', d.getDate());
                            cDay.on('mouseover', mouseOverEvent).on('mouseleave', mouseLeaveEvent);
                        }
                    }
                    cDay.html(day++);
                } else {
                    cDay.addClass('c-day-next-month c-pad-top');
                    cDay.html(dayOfNextMonth++);
                }
                cBody.append(cDay);
            }

I will suggest you to use ajax request.

Javascript : Ajax

        $.ajax({
            type: 'POST',
            url: '@URL.Action("Comments","Controller")',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            data: {},
            success: function (data) {
             var events = new Object();
                events = $.map(data.d, function (item, i) {
                    for (var j = 0; j < data.d.length; j++) {
                        var event = new Object();                            
                        var startDate = Date.parse(item.WhenHappens )
                        event.start = startDate;                           
                        event.title = item.Title;
                        event.backgroundColor = "#c6458c";
                        event.description = item.Description;
                        return event;
                    }
                })
                callCalender(events);
            },
            error:function(e){  

            }
        });

Controller

[Route("events")]
    [HttpPost]
    [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
    public ActionResult Comments()
    {
        var _events= _context.Events.OrderBy(c => c.ProductID).ToList(); //yes, I know, I should use repository in the best practice
        return Json(_events);
    }

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