Telerik Forums
UI for ASP.NET MVC Forum
1 answer
373 views
Hi There,
I need to use datapicker control in a tabstrip which is in a grid control. I am trying to bind date value to my datapicker control but it's coming as blank.
Following are different ways i have tried:

1:
tml.Kendo().DatePicker()
.Name("datepicker")
.Value("\\#= storageCharge.storageEndDate #\\")
.HtmlAttributes(new { style = "width:100px" }).ToClientTemplate()
)

And

@(Html.Kendo().DatePicker()
.Name("datepicker")
.Value("#= storageCharge.storageEndDate #")
.HtmlAttributes(new { style = "width:100px" }).ToClientTemplate()
)

Also if i bind the same way to a input control it works:

<input type="text" onchange="javascript:calcStorageFees()" value="#= storageCharge.storageEndDate #" id="strDate" on name="strDate" />
Dimiter Madjarov
Telerik team
 answered on 25 Oct 2013
1 answer
240 views
I am using the Restful Routing (http://restfulrouting.com/) library in my MVC5 project. Restful Routing gives me true REST based actions for my controllers. I'm trying to use the Kendo Grid in edit mode against these actions. Using the MVC wrapper, I have the following code for my data source:

.DataSource(ds => ds
   .Ajax()
   .Model(model => model.Id(mapping => mapping.Id))
   .Read(read => read.Action("list", "mappings").Type(HttpVerbs.Get))
   .Create(create => create.Action("create", "mappings").Type(HttpVerbs.Post))
   .Update(update => update.Action("update", "mappings").Type(HttpVerbs.Put))
   .Destroy(destroy => destroy.Action("destroy", "mappings").Type(HttpVerbs.Delete))
   .PageSize(20)
)
The actions there should resolve to the URL /mappings/{id} with the exception of Read and Create. When I look at the generated JavaScript code though, I get the following: 

"dataSource": {
    "transport": {
        "prefix": "",
        "read": {
            "url": "/mappings/list",
            "type": "GET"
        },
        "create": {
            "url": "/mappings",
            "type": "POST"
        }
    },
There are no definitions for the update or destroy actions. If I change .Action to .Url, then I'm able to apply an HttpVerb. I figure the Url is the way to go, but how do I get the models Id within the Url string? I thought that perhaps the CleintTemplate placeholders would work, but they don't, e.g.:

.Update(update => update.Url(Url.Action("Update", "Mappings", new { id = "#=Id#"})).Type(HttpVerbs.Put))
So, how can I get the Model's Id in a Url?

Thanks,
Damien

Rosen
Telerik team
 answered on 25 Oct 2013
7 answers
319 views
Hi am trying to bind my sitemap to the KendoUI Tabstrip. I am having no joy with the MVC Sitemap though.

If I rename the nodes in my .sitemap from mvcSiteMapNode to siteMapNode then all works. When I change it back to mvcSiteMapNode it won't work. Nothing renders on the page.

What is the correct way to do this?
Daniel
Telerik team
 answered on 25 Oct 2013
1 answer
131 views
Hello Team,

I am getting some issue in closing the Scheduler event Popup First time when I creates an event and opens the popup again to create an appointment event  then the event popup dosent closes on close button click.

Please have look on my code :

View :
@model IEnumerable<VisionDB.Models.Schedule>
@{
    ViewBag.Title = "Calendar";
}

@(Html.Kendo().Scheduler<VisionDB.Models.Schedule>()
    .Events(e =>
    {
        e.Edit("EditEvent");
       
    })
        .Name("scheduler")
        .Editable(true)
        .Date(@DateTime.Today.Date)
        .StartTime(new DateTime(2013, 6, 13, 10, 00, 00))
        .EndTime(new DateTime(2013, 6, 13, 23, 00, 00))
        
        .Height(600)
        .Views(views =>
    {
        views.DayView();
        views.WeekView(weekView => weekView.Selected(true));
        views.MonthView();
        views.AgendaView();
    })
 
    //.Resources(resource =>
    //{
    //    resource.Add(m => m.CustomerId)
    //        .Title("Owner")
    //        .DataTextField("Text")
    //        .DataValueField("Value")
    //        .DataColorField("Color")
    //        .BindTo(new[] {
    //            new { Text = "Alex", Value = 1, Color = "#f8a398" } ,
    //            new { Text = "Bob", Value = 2, Color = "#51a0ed" } ,
    //            new { Text = "Charlie", Value = 3, Color = "#56ca85" }
    //        });
    //})
    
        .Selectable(true)
        .Editable(true)
        .MajorTick(60)
        //.BindTo(Model)     
        .DataSource(d => d
            .Model(m =>
            {
               //m.Id(f => f.CustomerId);
               // m.Field(f => f.CustomerId).DefaultValue(1);

            })

        .Read("ReadSchedule", "Customers")
        .Create("CreateSchedule", "Customers")
        .Destroy("DestroySchedule", "Customers")
        .Update("UpdateSchedule", "Customers")

        )
    )


<script>
   
    function EditEvent(e) {
        $('.k-popup-edit-form.k-scheduler-edit-form.k-window-content.k-content').hide();
        $('.k-widget.k-window').append('<div id="DivSelectCustomerInner">' + $('#DivSelectCustomer').html() + '</div>');
        //$('#DivSelectCustomer').remove();
    }
    
    function CustomerSelected() {
        $('#DivSelectCustomerInner').hide();
        $('.k-popup-edit-form.k-scheduler-edit-form.k-window-content.k-content').show();
        //ICustomerId
        
       // $('#DivSelectCustomerInner').hide();
    }
    function SearchCustomer() {
        var sPath = '@Url.Action("SearchCustomer", "Customers")';
        var SearchData = $("#DivSelectCustomerInner #TxtFName").val();
        //var SurName = $("#DivSelectCustomerInner #TxtSName").val();
       
        $.ajax({
            type: 'POST',
            url: sPath,
            data: "{'SearchData': '" + SearchData + "'}",
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                WriteToCustomers(data);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    }
    function SelectCustomer(CustomerId,CustomerName) {
        var sPath = '@Url.Action("SetCustomerId", "Customers")';
        $.ajax({
            type: 'POST',
            url: sPath,
            data: "{'CustomerId': '" + CustomerId + "'}",
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $('#DivSelectCustomerInner #BtnNext').show(500);
                $('.k-edit-form-container').append('<input  type="hidden" id="HdnCustomerId" name="CustomerId" data-bind="value:CustomerId" value="' + CustomerId + '">');
                $('.k-window-title').html('Event - Selected Customer : ' + CustomerName);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    }

    function WriteToCustomers(data)
    {
        //alert(data);
        if (data) {
            if (data!=null) {
                var isdata = 0;
                var CustomerHTML = '<table>';
                if(data.length>0)
                {
                    //alert("passed length");
                    CustomerHTML += '<tr>';
                    CustomerHTML += '<td>Select </td>';
                    CustomerHTML += '<td>First Name </td>';
                    CustomerHTML += '<td>Surname </td>';
                    CustomerHTML += '<td>Address</td>';
                    CustomerHTML += '</tr>';
                    $.each($.parseJSON(data), function (key, value) {
                        isdata = 1;
                        CustomerHTML += '<tr>';
                        CustomerHTML += '<td><input type="button" value="Select" onclick="SelectCustomer(\'' + value.Id + '\',\'' + value.Firstnames + ' ' + value.Surname + '\' )" /> </td>';
                        CustomerHTML += '<td>' + value.Firstnames + '</td>';
                        CustomerHTML += '<td>' + value.Surname + '</td>';//
                        CustomerHTML += '<td>' + value.Address + '</td>';
                        CustomerHTML += '</tr>';
                    });
                    CustomerHTML += '</table>';
                    
                }
                //alert(CustomerHTML);
                if (isdata == 0) {
                    $('#SearchResultDiv').html('<p> No Customers Found</p>');
                } else {
                   // alert(CustomerHTML);
                    $('#DivSelectCustomerInner #SearchResultDiv').html(CustomerHTML);
                }
                
            }else{
                LoadAppointment(ScheduleId);
            }
        }
       
        //return false;
    }



</script>
<div id="DivSelectCustomer" style="display:none;">
    <h3 style="margin-left:15px;">Search Customer</h3>
    @*<div class="k-edit-label">  <label for="title">Search</label></div>*@
    <input type="text" class="k-input k-textbox" id="TxtFName" style="width:200px;margin-left:15px;margin-right:10px;"/><input type="button" class="k-button" value="Search" onclick="SearchCustomer()" />
    <br /><br />
    <div style="text-align:right"></div>
    <br />
    <div id="SearchResultDiv"></div>
    <br />
    <div class="k-edit-buttons k-state-default" style="text-align:right">
    <input type="button" id="BtnNext" class="k-button" style="display:none;" value="Next" onclick="CustomerSelected()" />
</div>

</div>
<div id="tempdiv"></div>

Controller :

using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using VisionDB.Helper;
using VisionDB.Models;
using System.Globalization;
using System.IO;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.Security;

namespace VisionDB.Controllers
{
    [Authorize]
    public class CustomersController : Controller
    {

        #region Customers
        public ActionResult Index()
        {
            return Search(null);
        }

        public ActionResult Search(string Search)
        {
            var db = new CustomersDataContext();
            var results = from row in db.Customers
                          select row;

            if (!string.IsNullOrWhiteSpace(Search))
            {
                results = results.Where(c => c.Number.ToLower().Contains(Search.ToLower())
                              || c.Number.Replace(" ", "").ToLower().Contains(Search.Replace(" ", "").ToLower())
                              || c.Firstnames.ToLower().Contains(Search.ToLower())
                              || c.Surname.ToLower().Contains(Search.ToLower())
                              || c.Address.ToLower().Contains(Search.ToLower())
                              || c.Postcode.ToLower().Contains(Search.ToLower())
                              || c.Postcode.Replace(" ", "").ToLower().Contains(Search.Replace(" ", "").ToLower())
                              || c.Telephone.ToLower().Contains(Search.ToLower())
                              || c.SMSNumber.ToLower().Contains(Search.ToLower())
                              || c.SMSNumber.Replace(" ", "").ToLower().Contains(Search.Replace(" ", "").ToLower())
                              || c.Email.ToLower().Contains(Search.ToLower()));
            }
            else
            {
                results = results.Where(c => false);
            }

            return View(results);
        }

        public ActionResult Customer(Guid Id,string message)
        {
            var db = new CustomersDataContext();
            //get customers by id
            var customer = db.Customers.Find(Id);
            customer.EyeTests = new EyeTestsController().GetEyeTests(customer);
             //get customer attachments
            customer.GetAttachments = GetCustomerAttachments();
            customer.Invoices = new InvoicesController().GetInvoices(customer);
            foreach (Invoice invoice in customer.Invoices)
            {
                invoice.InvoiceDetails = GetInvoices(invoice);
            }
            if (message != null)
            {
                @ViewBag.Message = message;
            }
            return View(customer);
        }

        [HttpGet]
        public ActionResult Edit(Guid Id)
        {
            var db = new CustomersDataContext();
            var customer = db.Customers.Find(Id);
            ViewBag.NHSPrivateLists = EnumHelper.ToSelectList(VisionDB.Models.Customer.NHSPrivateList.Unknown);
            ViewBag.SmokerLists = EnumHelper.ToSelectList(VisionDB.Models.Customer.SmokerList.Unknown);
         
            return View(customer);
        
      
        }

       

        [HttpPost]
        public ActionResult Edit([Bind(Exclude = "Age,LastTestDate,NextTestDueDate")]Models.Customer customer)
        {
            if (string.IsNullOrWhiteSpace(customer.Telephone) && string.IsNullOrWhiteSpace(customer.SMSNumber))
            {
                ModelState.AddModelError("Telephone", "Either a telephone or SMS number must be supplied");
                ModelState.AddModelError("SMSNumber", "Either a SMS or telephone number must be supplied");
            }

            if (ModelState.IsValid)
            {
                if (customer.Id == Guid.Empty)
                {
                    customer.Id = Guid.NewGuid();
                }

                //Save to database
                var db = new CustomersDataContext();

                db.Entry(customer).State = EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction("Customer", new { customer.Id });
            }

            return Edit(customer.Id);
        }

        [HttpGet]
        public ActionResult Create()
        {
            //populate drop down lists
            ViewBag.NHSPrivateLists = EnumHelper.ToSelectList(VisionDB.Models.Customer.NHSPrivateList.Unknown);
            ViewBag.SmokerLists = EnumHelper.ToSelectList(VisionDB.Models.Customer.SmokerList.Unknown);
            ViewBag.AppTypes = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.AppType.Eye_Test);
            return View();
        }

        [HttpPost]
        public ActionResult Create([Bind(Exclude = "Age,LastTestDate,NextTestDueDate")]Models.Customer customer)
        {
            if (string.IsNullOrWhiteSpace(customer.Telephone) && string.IsNullOrWhiteSpace(customer.SMSNumber))
            {
                ModelState.AddModelError("Telephone", "Either a telephone or SMS number must be supplied");
                ModelState.AddModelError("SMSNumber", "Either a SMS or telephone number must be supplied");
            }

            if (ModelState.IsValid)
            {
                if (customer.Id == Guid.Empty)
                {
                    customer.Id = Guid.NewGuid();
                }

                //Save to database
                var db = new CustomersDataContext();
                db.Customers.Add(customer);
                db.SaveChanges();

                return RedirectToAction("Customer", new { customer.Id });
            }

            return Create();
        }
        #endregion

        #region Eyetest

        public ActionResult EyeTest(Guid Id)
        {
            var db = new CustomersDataContext();

            var eyeTest = db.EyeTests.Find(Id);
            ViewBag.Customer = db.Customers.Find(eyeTest.CustomerId);
            
            return View(eyeTest);
        }

        [HttpGet]
        public ActionResult EditEyeTest(Guid Id)
        {
            var db = new CustomersDataContext();
            var eyeTest = db.EyeTests.Find(Id);
            ViewBag.Customer = db.Customers.Find(eyeTest.CustomerId);
            ViewBag.Bases = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.Base.None);
            ViewBag.AppTypes = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.AppType.Eye_Test);
            ViewBag.AdviceAndRecallLists = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.AdviceAndRecallList.None);
            ViewBag.AppRooms = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.AppRoom.One);
            ViewBag.YesNos = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.YesNo.None);
            ViewBag.LensTypes = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.LensType.Not_Assigned);
            return View(eyeTest);
        }

        [HttpPost]
        public ActionResult EditEyeTest([Bind]Models.EyeTest eyeTest)
        {
            if (eyeTest.TestDateAndTime == null)
            {
                ModelState.AddModelError("Test date", "A test date is required");
            }

            if (ModelState.IsValid)
            {
                if (eyeTest.Id == Guid.Empty)
                {
                    eyeTest.Id = Guid.NewGuid();
                }

                string signatureJson = Request.Form["output"];

                //Save to database
                var db = new CustomersDataContext();

                db.Entry(eyeTest).State = EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction("EyeTest", new { eyeTest.Id });
            }

            return EditEyeTest(eyeTest.Id);
        }

        [HttpGet]
        public ActionResult CreateEyeTest(Customer customer)
        {
            var db = new CustomersDataContext();
            var Customer = db.Customers.Find(customer.Id);
            ViewBag.Bases = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.Base.None);
            ViewBag.AppTypes = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.AppType.Eye_Test);
            ViewBag.AdviceAndRecallLists = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.AdviceAndRecallList.None);
            ViewBag.AppRooms = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.AppRoom.One);
            ViewBag.YesNos = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.YesNo.None);
            ViewBag.LensTypes = EnumHelper.ToSelectList(VisionDB.Models.EyeTest.LensType.Not_Assigned);
            ViewBag.Customer = Customer;

     return View();

        }

        [HttpPost]
        public ActionResult CreateEyeTest([Bind]Models.EyeTest eyeTest)
        {
            eyeTest.CustomerId = eyeTest.Id;

            if (eyeTest.Id == Guid.Empty)
            {
                eyeTest.Id = Guid.NewGuid();
            }

            //Save to database
            var db = new CustomersDataContext();
            var Customer = db.Customers.Find(eyeTest.CustomerId);

            eyeTest.Title = Customer.ToString() + " eye test";
            db.EyeTests.Add(eyeTest);
            db.SaveChanges();

            return RedirectToAction("EyeTest", new { eyeTest.Id });

        }
        #endregion

        #region Invoice
        public ActionResult Invoice(Guid Id)
        {
            var db = new CustomersDataContext();

            var invoice = db.Invoices.Find(Id);
            ViewBag.Customer = db.Customers.Find(invoice.CustomerId);
            invoice.InvoiceDetails = GetInvoices(invoice);
            return View(invoice);
        }

        private ICollection<InvoiceDetail> GetInvoices(Invoice invoice)
        {
            var db = new CustomersDataContext();

            var results = from row in db.InvoiceDetails
                          select row;

            if (invoice != null)
            {
                results = results.Where(c => c.InvoiceId == invoice.Id && c.UnitPrice >= 0);
            }
            else
            {
                results = results.Where(c => false);
            }

            var payments = from row in db.InvoiceDetails
                           select row;

            if (invoice != null)
            {
                payments = payments.Where(c => c.InvoiceId == invoice.Id && c.UnitPrice < 0);
            }
            else
            {
                payments = payments.Where(c => false);
            }

            return results.Union(payments).ToList();
        }
        [HttpGet]
        public ActionResult CreateInvoice(Guid Id)
        {
            var db = new CustomersDataContext();
            Invoice Invoice = new Invoice();
            Invoice.CustomerId = Id;
            ViewBag.Customer = db.Customers.Find(Id);
            return View(Invoice);
        }
        [HttpPost]
        public ActionResult CreateInvoice(string List, Invoice invoice)
        {
            List<InvoiceDetail> InvoiceDetailList = null;
            if (!string.IsNullOrEmpty(List) && invoice.InvoiceDate != null)
            {
                InvoiceDetailList = (List<InvoiceDetail>)Newtonsoft.Json.JsonConvert.DeserializeObject(List, typeof(List<InvoiceDetail>));
            }
            else
            {
                ModelState.AddModelError("Invoice", "No invoice detail lines");
            }
            if (ModelState.IsValid)
            {
                using (CustomersDataContext db = new CustomersDataContext())
                {
                    ViewBag.Customer = db.Customers.Find(invoice.CustomerId);

                    if (invoice.Id == Guid.Empty)
                    {
                        invoice.Id = Guid.NewGuid();
                        invoice.UserId = 1;
                    }

                    //Save to database              
                    invoice.CreatedTimestamp = DateTime.Now;
                    db.Entry(invoice).State = EntityState.Modified;
                    db.Invoices.Add(invoice);
                    int result = db.SaveChanges();

                    if (result == 1)
                    {
                        foreach (var Detaillst in InvoiceDetailList)
                        {
                            Detaillst.InvoiceId = invoice.Id;
                            if (Detaillst.Id == Guid.Empty)
                            {
                                Detaillst.Id = Guid.NewGuid();
                            }
                            db.Entry(Detaillst).State = EntityState.Modified;
                            db.InvoiceDetails.Add(Detaillst);
                            db.SaveChanges();
                        }
                    }
                    return Json(new { HasError = false, Message = "Success" });
                }
            }

            return Json(new { HasError = true, Message = "Invoice not created! please add invoice detail lines" });
        }

        [HttpGet]
        public ActionResult EditInvoice(Guid Id)
        {
            var db = new CustomersDataContext();
            var invoice = db.Invoices.Find(Id);
            ViewBag.Customer = db.Customers.Find(invoice.CustomerId);
            Session["InvoiceId"] = Id;
            invoice.InvoiceDetails = GetInvoices(invoice);
            return View(invoice);
        }

        [HttpPost]
        public ActionResult EditInvoice([Bind]Models.Invoice invoice)
        {
            //if (invoice.InvoiceDetails.Count == 0)
            //{
            //    ModelState.AddModelError("Invoice", "No invoice detail lines");
            //}

            if (ModelState.IsValid)
            {
                if (invoice.Id == Guid.Empty)
                {
                    invoice.Id = Guid.NewGuid();
                }

                //Save to database
                var db = new CustomersDataContext();
                invoice.CreatedTimestamp = DateTime.Now;
                db.Entry(invoice).State = EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction("Invoice", new { invoice.Id });
            }

            return EditInvoice(invoice.Id);
        }

        public ActionResult EditingInline_Read([DataSourceRequest] DataSourceRequest request, Guid Id)
        {
            if (Id != Guid.Empty)
            {
                return Json(SessionInvoiceRepository.All().Where(x => x.InvoiceId == Id).ToDataSourceResult(request));
            }
            return Json(null);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingInline_Create([DataSourceRequest] DataSourceRequest request, InvoiceDetail invoiceDetail, string Mode)
        {
            if (Mode != "Create")
            {
                if (invoiceDetail != null)
                {
                    invoiceDetail.InvoiceId = (Guid)Session["InvoiceId"];
                    SessionInvoiceRepository.Insert(invoiceDetail, Mode);
                }
            }
            else
            {
                if (invoiceDetail != null)
                {
                    SessionInvoiceRepository.Insert(invoiceDetail, Mode);
                }
            }
            
            return Json(new[] { invoiceDetail }.ToDataSourceResult(request));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingInline_Update([DataSourceRequest] DataSourceRequest request, InvoiceDetail invoiceDetail)
        {
            if (invoiceDetail != null && ModelState.IsValid)
            {
                var target = SessionInvoiceRepository.One(p => p.Id == invoiceDetail.Id);
                if (target != null)
                {
                    target.Description = invoiceDetail.Description;
                    target.UnitPrice = invoiceDetail.UnitPrice;
                    target.Quantity = invoiceDetail.Quantity;
                    target.ProductTypeId = invoiceDetail.ProductTypeId;
                    SessionInvoiceRepository.Update(target);
                }
            }
            return Json(new[] { invoiceDetail }.ToDataSourceResult(request, ModelState));            
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingInline_Destroy([DataSourceRequest] DataSourceRequest request, InvoiceDetail invoiceDetail)
        {
            if (invoiceDetail != null)
            {
                SessionInvoiceRepository.Delete(invoiceDetail);
            }
            
            //return RedirectToAction("EditInvoice", "Customers", new { Id = invoiceDetail.InvoiceId });                        
            return Json(new[] { invoiceDetail }.ToDataSourceResult(request, ModelState));
        }
        #endregion

        #region Calendar

        public ActionResult Calendar()
        {
            using (CustomersDataContext db = new CustomersDataContext())
            {
                List<Schedule> getSchedules = (from b in db.EyeTests
                                               select new Schedule
                                               {
                                                   Id = b.Id,
                                                   CustomerId = b.CustomerId,
                                                   Title = b.Title,
                                                   TestDateAndTime = b.TestDateAndTime,
                                                   Start = b.Start.HasValue ? b.Start.Value : b.TestDateAndTime,
                                                   End = b.Start.HasValue ? b.End.Value : b.TestDateAndTime,
                                                   Description=b.Notes
                                               }).ToList();

                return View(getSchedules);
            }
        }
        public virtual JsonResult ReadSchedule([DataSourceRequest] DataSourceRequest request)
        {
            using (CustomersDataContext db = new CustomersDataContext())
            {
                List<Schedule> getSchedules = (from b in db.EyeTests
                                               select new Schedule
                                               {
                                                   Id = b.Id,
                                                   CustomerId = b.CustomerId,
                                                   Title = b.Title,
                                                   TestDateAndTime = b.TestDateAndTime,
                                                   Start = b.Start.HasValue?b.Start.Value:b.TestDateAndTime,
                                                   End = b.Start.HasValue ? b.End.Value : b.TestDateAndTime
                                               }).ToList();

                return Json(getSchedules.ToDataSourceResult(request));
            }
        }
        [HttpPost]
        public JsonResult SearchCustomer(string SearchData)
        {
            using (CustomersDataContext db = new CustomersDataContext())
            {
                List<Customer> GetCustomers = (from Customers in db.Customers
                                               where Customers.Firstnames.Contains(SearchData) || Customers.Surname.Contains(SearchData) ||
                                               Customers.Address.Contains(SearchData) || Customers.Telephone.Contains(SearchData)
                                               select Customers  ).ToList();

                String json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(GetCustomers);
                return Json(json, JsonRequestBehavior.AllowGet);
               
            }
        }

        public virtual ActionResult DestroySchedule([DataSourceRequest] DataSourceRequest request, Schedule schedule)
        {
            if (schedule != null)
            {
                if (schedule.Id != Guid.Empty)
                {
                    using (CustomersDataContext dbContext = new CustomersDataContext())
                    {
                        EyeTest eyetest = dbContext.EyeTests.Where(x => x.Id == schedule.Id).FirstOrDefault();
                        dbContext.Entry(eyetest).State = EntityState.Modified;
                        dbContext.EyeTests.Remove(eyetest);
                        dbContext.SaveChanges();
                    }
                }
            }
            //using (CustomersDataContext db = new CustomersDataContext())
            //{
            //    List<Schedule> getSchedules = (from b in db.EyeTests
            //                                   select new Schedule
            //                                   {
            //                                       Id = b.Id,
            //                                       CustomerId = b.CustomerId,
            //                                       Title = b.Title,
            //                                       TestDateAndTime = b.TestDateAndTime,
            //                                       Start = b.Start.HasValue ? b.Start.Value : b.TestDateAndTime,
            //                                       End = b.Start.HasValue ? b.End.Value : b.TestDateAndTime,
            //                                       Description = b.Notes
            //                                   }).ToList();

            //    //return View(getSchedules);
            //}
            //return RedirectToAction("Calendar", "Customers");            
            return Json(new[] { schedule }.ToDataSourceResult(request, ModelState));
        }
        [HttpPost]
        public JsonResult SetCustomerId(string CustomerId)
        {
            Session["SelectedCustomerId"] = CustomerId;
            return Json("Success");
        }
        public virtual ActionResult CreateSchedule([DataSourceRequest] DataSourceRequest request, Schedule schedule)
        {
            if (schedule != null)
            {
                using (CustomersDataContext dbContext = new CustomersDataContext())
                {
                    EyeTest eyetest = new EyeTest();
                    if (schedule.Id == Guid.Empty)
                    {
                        Guid CustomerId = Guid.Parse(Session["SelectedCustomerId"].ToString());
                        eyetest.Id = Guid.NewGuid();
                        eyetest.TestDateAndTime = System.DateTime.Now;
                        //eyetest.Start = ConvertDateFormat(schedule.Start.ToString());
                        //eyetest.End = ConvertDateFormat(schedule.End.ToString());
                        eyetest.Title = schedule.Title;
                        eyetest.Notes = schedule.Description;
                        // Replace below customerId from selected CustomerId
                        //eyetest.CustomerId = Guid.Parse("057982f7-5aa1-4850-9de8-10aa264ede76");
                        eyetest.CustomerId = CustomerId;
                        eyetest.UserId = 1;
                        dbContext.EyeTests.Add(eyetest);
                        dbContext.SaveChanges();
                    }
                }
            }
           return RedirectToAction("Calendar", "Customers");
            //return Json(new[] { schedule }.ToDataSourceResult(request));
        }

        public virtual ActionResult UpdateSchedule([DataSourceRequest] DataSourceRequest request, Schedule schedule)
        {
            if (ModelState.IsValid)
            {
                if (schedule != null)
                {
                    using (CustomersDataContext dbContext = new CustomersDataContext())
                    {
                        if (schedule.Id != Guid.Empty)
                        {
                            EyeTest target = dbContext.EyeTests.Where(p => p.Id == schedule.Id).FirstOrDefault();
                            target.TestDateAndTime = ConvertDateFormat(schedule.TestDateAndTime.ToString());
                            target.Start = ConvertDateFormat(schedule.Start.ToString());
                            target.End = ConvertDateFormat(schedule.End.ToString());
                            target.Notes = schedule.Description;
                            target.Title = schedule.Title;
                            dbContext.Entry(target).State = EntityState.Modified;
                        }
                        dbContext.SaveChanges();
                    }
                }
            }
            
            return RedirectToAction("Calendar", "Customers");
            //return Json(new[] { schedule }.ToDataSourceResult(request, ModelState));
        }

        public DateTime ConvertDateFormat(string date)
        {
            DateTimeFormatInfo dateTimeFormatterProvider = DateTimeFormatInfo.CurrentInfo.Clone() as DateTimeFormatInfo;
            dateTimeFormatterProvider.ShortDatePattern = "MM/dd/yyyy HH:mm:ss"; //source date format
            DateTime dateTime = DateTime.Parse(date, dateTimeFormatterProvider);
            string formatted = dateTime.ToString("dd/MM/yyyy HH:mm:ss");
           return Convert.ToDateTime(formatted);
        }
        #endregion

        #region Attachments
        public ActionResult UploadAttachments(IEnumerable<HttpPostedFileBase> files, string Comments, Guid Id, int AttachmentId = 0)
        {
            string fileName = string.Empty;
            if (files != null)
            {
                foreach (var file in files)
                {
                    if (file.ContentLength > 0)
                    {
                        fileName = Path.GetFileName(file.FileName);
                        string urlPath = string.Format("{0}{1}", Server.MapPath("~/content/uploads/"), Id);
                        var path = Path.Combine(urlPath, fileName);
                        // Create directory as necessary and save image
                        if (!Directory.Exists(urlPath) && !System.IO.File.Exists(path))
                        {
                            Directory.CreateDirectory(urlPath);
                            file.SaveAs(path);
                        }
                    }
                }
            }
            if (AttachmentId == 0)
            {
                using (var entities = new CustomersDataContext())
                {
                    Attachments attachments = new Attachments();
                    attachments.FileName = fileName;
                    attachments.FileComments = Comments;
                    attachments.CustomerId = Id;
                    //check file already exist and if not save the attachments
                    bool Isfilealreadyexists = entities.Attachments.Where(m => m.FileName == attachments.FileName).Any();
                    if (!Isfilealreadyexists)
                    {
                        entities.Attachments.Add(attachments);
                        int i = entities.SaveChanges();
                    }
                    else
                    {
                        ViewBag.Message = "File already exist! please delete the existing one and upload again";
                    }

                }
            }
            else
            {
                EditAttachments(AttachmentId, Comments, Id);
            }
            return RedirectToAction("Customer", new { Id = Id, message = ViewBag.Message });
        }

        public ActionResult EditAttachments(int id, string Comments, Guid customerId)
        {
            using (var entities = new CustomersDataContext())
            {
                //get and edit the attachments
                Attachments data = entities.Attachments.Where(m => m.Id == id).FirstOrDefault();
                data.FileComments = Comments;
                entities.SaveChanges();
            }
            return RedirectToAction("Customer", new { id });
        }
        public IEnumerable<Attachments> GetCustomerAttachments()
        {
            using (var entities = new CustomersDataContext())
            {
                //get customers by id
                return entities.Attachments.ToList();
            }
        }

        public ActionResult Delete(int Id)
        {
            Attachments data = null;
            using (var entities = new CustomersDataContext())
            {
                //delete the customer
                data = entities.Attachments.Where(m => m.Id == Id).FirstOrDefault();
                entities.Attachments.Remove(data);
                entities.SaveChanges();
            }
            //to delete the file from the folder
            string urlPath = string.Format("{0}{1}", Server.MapPath("~/content/uploads/"), data.CustomerId);
            var path = Path.Combine(urlPath, data.FileName);
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
            return RedirectToAction("Customer", new { Id = data.CustomerId });
        }
        #endregion

        public ActionResult Recalls(string DueDateDays, string LastRecallDays)
        {

            if (DueDateDays == null || DueDateDays.Length == 0)
            {
                DueDateDays = "30";
            }

            if (LastRecallDays == null || LastRecallDays.Length == 0)
            {
                LastRecallDays = "5";
            }
            DateTime dueDateCutOff = DateTime.Now.Date.AddDays(Convert.ToInt32(DueDateDays));

            var db = new CustomersDataContext();
            var results = from row in db.Customers
                          select row;

            results = results.Where(c => c.NextTestDueDate.HasValue == false
                || (c.NextTestDueDate.Value < dueDateCutOff
                && c.LastRecallDate == null));

            return View(results);
        }

        public ActionResult SendRecalls(Customer customer, FormCollection form)
        {
            string[] rawselectedids = form.Get("SelectedIds").Split(',');
            int recallMethod = Convert.ToInt32(Request.Form["Filter"]);
            List<Guid> selectedIds = new List<Guid>();

            foreach (string id in rawselectedids)
            {
                if (id.Length > 1)
                {
                    selectedIds.Add(new Guid(id.Replace("chkbox", "")));
                }
            }

            SendRecallMessages(selectedIds, recallMethod);

            TempData["OutboxMessage"] = string.Format("{0} recalls sent", selectedIds.Count);

            return RedirectToAction("Outbox");
        }

        private void SendRecallMessages(List<Guid> selectedIds, int recallMethod)
        {
            var db = new CustomersDataContext();
            var results = from row in db.Customers
                          select row;

            results = results.Where(model => selectedIds.Contains(model.Id));

            string template = db.MessageTemplates.Find(recallMethod).Template;

            foreach (Customer customer in results)
            {
                if (customer.SMSNumber != null && customer.SMSNumber.Length > 5)
                {
                    MembershipUser u = Membership.GetUser(User.Identity.Name);
                    
                    Message message = new Message();
                    message.Id = Guid.NewGuid();
                    message.RecipientId = customer.Id;
                    message.MessageTypeId = recallMethod;
                    message.SenderUserId = (int)u.ProviderUserKey;
                    message.ToAddressNumber = customer.SMSNumber;
                    message.MessageText = string.Format(template,
                        customer.TitleAndName(), customer.NextTestDueDate.Value.ToShortDateString(), customer.SMSNumber); //todo: get number for practice
                    message.AddedToQueue = DateTime.Now;
                    message.Cancelled = null;
                    message.CancelledByUserId = null;
                    message.Sent = null;

                    db.Messages.Add(message);
                }
                else
                {
                    //handle where sms doesn't exist or too short
                }
            }

            db.SaveChanges();
        }
        
        public ActionResult Outbox()
        {
            var db = new CustomersDataContext();

            var results = from row in db.Messages
                          select row;

            results = results.Where(m => m.Sent == null && m.Cancelled == null);


            return View(results);
        }
    }
}

Modal :

  public class Schedule : ISchedulerEvent
    {
        public Guid Id { get; set; }
        public Guid CustomerId { get; set; }
        public string Description { get; set; }
        public DateTime TestDateAndTime { get; set; }
        public string Title { get; set; }
        public DateTime Start { get; set; }
        public DateTime End { get; set; }        
        public bool IsAllDay { get; set; }
        public string Recurrence { get; set; }
        public string RecurrenceRule { get; set; }
        public string RecurrenceException { get; set; }
       // public int ICustomerId { get; set; }
    }
Vladimir Iliev
Telerik team
 answered on 25 Oct 2013
0 answers
95 views
Hello,

    I am a Telerik newbie so this may be an easy answer:

I have view with several Grids.

The grid in question ("WorkSpace") get loaded based on user input. The grid renders with the proper data and also can save edits properly.
However, whenever I reload the Grid it will not pull the updated  data. The db code behind data methods are not getting called/Executed. Grid just reloads old dataset

Question:  How can I force grid to render with latest data rather than cached?

function loadDataProfile(id) {
var result = true;
var rows;
var grid = $("#WorkingSeries").data("kendoGrid");

$.ajax({ url: baseUrl + '/EyascoDB/GetDataProfile?id=' + id,
async: false,
type: 'GET',
dataType: 'JSON',
success: function (data) {
$("#txtProfileName").val(data[0].dprOwner + " / " + data[0].dprName)
if (data[0].dprPublic) {
$("#txtProfileName").css("color", "green");
} else {
$("#txtProfileName").css("color", "blue");
}
},
error: function () {
result = false;
}
});

$.ajax({ url: baseUrl + '/EyascoDB/GetProfileSeriesByProfileID?id=' + id,
async: false,
type: 'GET',
dataType: 'JSON',
success: function (data) {
rows = data;
},
error: function () {
result = false;
}
});

for (var i = 0; i < rows.length; i++) {
grid.dataSource.add({
id: rows[i].id,
Type: rows[i].Type,
Name: rows[i].Name,
Lookup: rows[i].Lookup,
Units: rows[i].Units,
StartDate: dateFormat(new Date(parseInt(rows[i].StartDate.substring(6)))),
EndDate: dateFormat(new Date(parseInt(rows[i].EndDate.substring(6)))),
HideQAFail: rows[i].HideQAFail,
MultiChart: rows[i].MultiChart
});

$.ajax({ url: baseUrl + '/EyascoDB/GetSeriesDetailsBySeriesID?ProfileID=' + id + '&RowID=' + rows[i].id,
async: false,
type: 'GET',
dataType: 'JSON',
success: function (data) {
details = data;
},
error: function (errorMsg) {
var e = errorMsg
result = false;
}
});

//adds the associated Series Details
sd = new Object();
// sd.ShowGaps = false;
sd.NativeTimeSteps = details.NativeTimeSteps;
sd.GapHandlingAlgorithm = details.GapHandlingAlgorithm;
sd.ShowQuality = details.ShowQuality;
seriesDetails.push(sd);
}

return result;
}
Dan
Top achievements
Rank 1
 asked on 25 Oct 2013
3 answers
742 views
I am using java script and the client template to calculate and display the row index for the grid, which is working just fine.  A new requirement came in and now I have to actually store the int into the database.  I tried binding the column to the object but since it is client side the object doesn't get the value from the grid.  I also tried use the default when adding a new row but I could not find a way to increment the variable, it is always "1".  

Is there a way to get the client template value into the cell so I can submit the value to the database?

@model DetailsViewModel
@{
    var case = Model.Case;
}
 
@(Html.Kendo().Grid<GridViewModel>()
      .Name("Grid")
      .Columns(columns =>
          {
              columns.Bound(m => m.ProductId)
                  .Visible(false);
              columns.Bound(m => m.Label)
                  .ClientTemplate("#= renderNumber() #")
                  .Title("#");
              columns.Bound(m => m.PerceivedProblem)
                  .Title("Perceived Problem")
                  .Width(100);
              columns.Bound(m => m.Site)
                  .ClientTemplate("#= Site ? Site.LabName : '' #")
                  .Title("Location")
                  .Width(150);
              columns.Bound(m => m.DateOpened)
                  .Title("Date Opened");
              columns.Bound(m => m.DateReceived)
                  .Title("Date Received");
              columns.Command(command => command.Destroy())
                  .Width(150);
          })
      .Editable(editable => editable.Mode(GridEditMode.InCell))
      .ToolBar(toolBar =>
          {
              toolBar.Create();
              toolBar.Save();
          })
      .Navigatable()
      .DataSource(dataSource => dataSource
            .Ajax()
            .PageSize(15)
            .Events(events =>
                {
                    events.Error("error_handler");
                    events.Change("resetRowNumber");
                })
            .Batch(true)
            .ServerOperation(false)
            .Model(model =>
                {
                    model.Id(m => m.Id);
                    model.Field(m => m.ProductId);
                    model.Field(m => m.Label).Editable(false);
                    model.Field(m => m.Site).DefaultValue(new Site { LabName = string.Empty });
              })
            .Read(read => read.Action("GridAjaxRead", "Home", new { case}))
            .Create(create => create.Action("GridAjaxCreate", "Home", new { case }))
            .Update(update => update.Action("GridAjaxUpdate", "Home"))
            .Destroy(destroy => destroy.Action("GridAjaxDestroy", "Home"))
      )
      .Resizable(resize => resize.Columns(true)))
 
<script type="text/javascript">
    function error_handler(e) {
        alert("Server error");
    }
    var rowNumber = 0;
 
    function resetRowNumber() {
        rowNumber = 0;
    }
 
    function renderNumber() {
        return ++rowNumber;
    }
</script>
steve
Top achievements
Rank 1
 answered on 24 Oct 2013
1 answer
100 views
some of the data in my foreign key column (loaded from database) contains a # character. How do I properly escape that?

I am loading data just like the foreign key column example in the MVC example.

Without doing anything the grid fails to load and display anything.

I tried a single backspace "\#" (controller complains not proper escape sequence)

I used a double "\\#" which loads the grid but displays Item \#1 vs. Item #1

What is the proper way to escape this # character?
Daniel
Telerik team
 answered on 24 Oct 2013
1 answer
2.4K+ views
I am stuck with two problems related to the DateTimePicker and the DatePicker.

We have a checkbox in the view where the user can enable/disable the time selector (date only or date/time), and another checkbox for 24 hour range for which I want to disable the To Date DatePicker (have both a FromDate and ToDate pickers).

What I would like to know is..
1. How to disable/enable a DatePicker.
2. How to switch it from date to date/time and back to date again - dependent on the checkbox selection above.

Controls and script in my view. Pretty simple stuff, but my toDatePicker var does not allow me to enable/disable the control. It just does nothing.
I have not done any code yet for changing the date picker between date only and date/time. I cannot even disable the control, so not looked at this yet. Would appreciate a heads up on how to do this please.

Also open to a better way to what I have indicated below.
@Html.EditorFor(x => x.SelectByDateAndTime)
@Html.CheckBoxFor(x => x.TwentyFourHourShift)
@Html.LabelFor(x => x.DateFrom, new { id = "FromDateLabel"})
@Html.EditorFor(x => x.DateFrom)
@Html.EditorFor(m => m.DateTo)
 
$(document).ready(function () {       
        var fromDateLabel = $("#FromDateLabel");       
        var toDatePicker = $("#DateTo").data("kendoDateTimePicker");
        var twentyFourHourShiftCheckBox = $("#TwentyFourHourShift");
        var selectByDateTimeCheckBox = $("#SelectByDateAndTime");
         
        twentyFourHourShiftCheckBox.click(function () {
            if (twentyFourHourShiftCheckBox.attr('checked')) {
                selectByDateTimeCheckBox.attr("disabled", true);
                fromDateLabel.text("For Date");               
            }
            else {
                selectByDateTimeCheckBox.removeAttr("disabled");
                fromDateLabel.text("From Date");               
            }
             
            toDatePicker.enable();
        });
         
        selectByDateTimeCheckBox.click(function () {
            if (selectByDateTimeCheckBox.attr('checked'))
                twentyFourHourShiftCheckBox.attr("disabled", true);
            else
                twentyFourHourShiftCheckBox.removeAttr("disabled");
 
            toDatePicker.enable();
        });
    });
Petur Subev
Telerik team
 answered on 24 Oct 2013
22 answers
5.0K+ views
Hello I have been evaluating Kendo UI for ASP.NET MVC  version 2012.2.710 for a while now and it looks as if I will be recommending we buy a license.
.
I have searched your documentation for a long time trying to find how to implement a custom grid filter rather than use the built in filters.
I am thinking along the lines of having some text and combo boxes above the grid, together with a "Filter" Button.
Eg. First Name: TEXTBOX  Last Name: TEXTBOX  Country: COMBOBOX             FILTERBUTTON
When the user clicks the FILTERBUTTON, the grid will display records according to the contents of the the above.

I am sure the answer must be somewhere in the documentation as I imagine this is a common requirement,  however I just can't find it.

It would be great if you could give me an example or, failing that, point me in the in the right direction.

Many thanks.
Deej
Top achievements
Rank 1
 answered on 23 Oct 2013
1 answer
134 views
I have couple of issues after implementing the keyboard navigation in the Kendo grid.

Issue 1: I need the entire row to be selected when the user tries to edit the column by using keyboard navigation. But currently the row selection happens if
we use mouse or by pressing the “Space Bar” key while navigating through the keyboard.

I need to avoid the row selection, which happens after pressing space bar key and need to implement it when the user tries to edit the cell.

Reason: I need to update the values of other columns when the user edits one column. I have implemented it using the grid selection row.Please refer the
below code for it.

//To validate the user inputs
    function onSave(e) {
        var grid = $a('#GrdPlanOrderToMachine').data("kendoGrid");
        var select;
        var data;
        if (e.values["PlanningInd"] != undefined) {
            if (e.values["PlanningInd"] == "N") {
                $("#confirmationDialog").dialog({
                    resizable: false,
                    height: 150,
                    modal: true,
                    buttons: {
                        "Yes": function () {
                            // Access the row that is selected
                            select =grid.select();
                            // select the data
                            data =grid.dataItem(select);
                            // update the column `Machine` and set its value to `0`
                            data.set("MachineId", 0);
                            // update the column `Status` and set its value to `REC`
                            data.set("Status", "REC");
                            data.set("OrderStatus",0);
                            // update the column `PlanningSeq` and set its value to 9999`
                            data.set("PlanningSeq",9999);
                            $(this).dialog("close");
                        },
                        "No": function () {
                            $(this).dialog("close");
                            select =grid.select();
                            //select the data
                            data =grid.dataItem(select);
                            // update the column `PlanningInd` and set its value to`Y`
                            data.set("PlanningInd", "Y");
                            e.preventDefault();
                        }
                    }
                });
            }
        }
    };

Issue 2:  I have a combo box for a column, which contains value as "Y" or "N". I am able to expand the Combo Box in single click before implementing the keyboard Navigation, but after implementing the key board navigation, I am able to expand the combo box after clicking thrice or more time. I have written the below code in the Edit event. 

 //To protect the cell/entire row from editing based on different condition
    function onEdit(e) {
        //For Planning Ind - We are not able set this based on column name hence referring the index
        if (e.container[0].cellIndex == 14) {
            if (e.model.BundleInd != null) {
                if (e.model.BundleInd.toUpperCase() == 'Y') {
                    this.closeCell();
                }
            }
        }
    }

Thanks in Advance,
Regards,
Sreejesh
Nikolay Rusev
Telerik team
 answered on 23 Oct 2013
Narrow your results
Selected tags
Tags
+133 more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?