Telerik Forums
UI for ASP.NET MVC Forum
2 answers
454 views
Hello,
i've implemented a custom comand delete-button for inline-editing. if clicked, a popup fades in and i have the choice to click "yes" or "no" for delete confirmation.
but on controller the delete-event is triggered twice and throws errors. what is wrong with my code? hope you can help me.

Grid:
@(Html.Kendo().Grid(Model)
    .Name("Adressen")
     
    // Datasource
    .DataSource(dataSource => dataSource
        .Ajax()
        .AutoSync(true)
        .PageSize(250)
        .Model(model =>
        {
            model.Id(p => p.Eadr);
            model.Field(p => p.Eadr).Editable(false);
            model.Field(p => p.BaLand).DefaultValue(new LiCPSAdmin2.Models.BaLand());
        })
        .Events(events => events.Error("adressen_error_handler"))
        .Create(create => create.Action("Create", "Adressen"))
        .Read(read => read.Action("Read", "Adressen"))
        .Update(update => update.Action("Edit", "Adressen"))
        .Destroy(destroy => destroy.Action("Delete", "Adressen"))
    )
     
    //Columns
    .Columns(columns =>
    {
        columns.Command(command =>
        {
            command.Edit().Text(" ");
            command.Custom(" ").Click("adressen_delete_handler").HtmlAttributes(new { name = "btn_delete"});
        }).Width(90).HtmlAttributes(new { style = "background-color: rgb(238, 238, 238)" });
        columns.Bound(p => p.Eadr).Width(90).HtmlAttributes(new { style = "text-align:center;" });
        columns.Bound(p => p.Nama);
        columns.Bound(p => p.Namb);
        columns.Bound(p => p.Namc);
        columns.Bound(p => p.Namd);
        columns.Bound(p => p.Name);
        columns.Bound(p => p.Namf);
        columns.Bound(p => p.Pstc).Width(90).HtmlAttributes(new { style = "text-align:center;" });
        columns.Bound(p => p.Ccty).Width(90).HtmlAttributes(new { style = "text-align:center;" });
        columns.Bound(p => p.BaLand.Dsca)
            .Width(200)
            .ClientTemplate(" #= BaLand ? BaLand.Dsca : '' # ")
            .Filterable(f => f.UI("statesFilter"));
    })
     
    // Events
    .Events(events => events.Edit("adressen_edit_handler")
        .DataBound("adressen_bound_handler"))
         
    // Options
    .ToolBar(toolbar => toolbar.Create().HtmlAttributes(new { enabled = "false" }))
    .Editable(editable => editable.Mode(GridEditMode.InLine).DisplayDeleteConfirmation(false))
    .Pageable()
    .Sortable()
    .Filterable(filter => filter.Extra(false))
    .Scrollable(scrollable => scrollable.Virtual(true))
    .HtmlAttributes(new { style = "height:100%;" })
    .Resizable(resize => resize.Columns(true))
    .ColumnResizeHandleWidth(5)
    .Reorderable(reordering => reordering.Columns(false))
)
Javascript:
function adressen_delete_handler(e) {
    e.preventDefault();
 
    var grid = this;
    var row = $(e.currentTarget).closest("tr");
     
    $("#delete_confirmation_popup").css({'top': ($(row).position().top + 157 + ($(row).height() / 2)), 'margin-left': (86)}).fadeIn();
 
    $("#btn_yes").off().on('click',function () {
        grid.removeRow(row);
        $("#delete_confirmation_popup").fadeOut();
    });
 
    $("#btn_no").off().on('click',function () {
        grid.cancelChanges();
        $("#delete_confirmation_popup").fadeOut();
    });
};
Thanks for help! :)
Helga
Top achievements
Rank 1
 answered on 28 Oct 2013
14 answers
735 views
I'm not sure if this is an issue my grid configuration or just a general MVC issue I am having but I've got a grid in a partial view and when I try to delete an item it is posting to the parent view controller method instead of the method I have configured in the grid.  I believe I have the views configured correctly but I must be missing something.

View:
@model PASS.ViewModels.Proposals.RequiredViewModel
 
@using (Ajax.BeginForm("Required", "Proposals", new AjaxOptions { UpdateTargetId = "requiredReturnMsg", HttpMethod = "Post" }))
{
  
@Html.HiddenFor(model => model.Proposal_ID, Model.Proposal_ID)
 
<div class="editor-container">
 
    <div class="editor-label">
        @Html.Label("Funding Source")
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.Funding_Source_ID,  new SelectList(Model.FundingSources, "Value",  "Text"), "(Select One)")
        @Html.ValidationMessageFor(model => model.Funding_Source_ID)
    </div>   
    <br class="clear" />
    <div class="editor-label">
        @Html.Label("Specify (only if requested)")
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.Funding_Specify, new { style = "width: 350px;" })
        @Html.ValidationMessageFor(model => model.Funding_Specify)
    </div>
    <br class="clear" />
    <br />
    <br />
    <p><input type="submit" value="Add Funding Source" /></p>
    <br />
    <br />
    @Html.Action("FundingSources", "Proposals", new { proposalID = Model.Proposal_ID })
    <br />
    <br />
 
    <div id="requiredReturnMsg"></div>
 
</div>
     
}
The partial view is called by the @Html.Action

Partial View:
@model IEnumerable<PASS.ViewModels.Proposals.FundingSourcesViewModel>
    
@using (Ajax.BeginForm("FundingSources", "Proposals", new AjaxOptions { }))
{
 
<div style="width:95%;">
@(Html.Kendo().Grid(Model)
    .Name("gvFundingSources") 
    .Columns(columns =>
    {
        columns.Bound(o => o.FundingSourceDescription).Title("Funding Source");
        columns.Bound(o => o.Funding_Specify).Title("Specifics");
        columns.Command(command => { command.Destroy(); }).Width(50);
    })
    .Sortable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model => model.Id(o => o.ID))
        .Read(read => read.Action("FundingSources", "Proposals"))
        .Destroy(destroy => destroy.Action("DeleteFundingSource", "Proposals"))
    )
)
</div>
     
}

Controller Methods:
public ActionResult Required(int proposalID)
{
    var context = new PASSEntities();
 
    RequiredViewModel model = new RequiredViewModel
    {
        Proposal_ID = proposalID,
        FundingSources = context.Funding_Sources.ToList().Select(m => new SelectListItem { Value = m.ID.ToString(), Text = m.Description }).ToList()
    };
 
    return PartialView(model);
}
 
[HttpPost]
public ActionResult Required(RequiredViewModel model)
{
    try
    {
        var context = new PASSEntities();
        var fundingsource = context.Proposal_Funding_Sources.Find(model.ID);
        bool bAdd = false;
 
        if (fundingsource == null) {
            fundingsource = new Proposal_Funding_Sources();
            bAdd = true;
        }
 
        fundingsource.Funding_Source_ID = model.Funding_Source_ID;
        fundingsource.Proposal_ID = model.Proposal_ID;
        fundingsource.Funding_Specify = model.Funding_Specify;
 
        if (bAdd) context.Proposal_Funding_Sources.Add(fundingsource);
        else context.Entry(fundingsource).State = System.Data.EntityState.Modified;
        context.SaveChanges();
 
        var message = new SystemMessage(Models.eMessageType.SUCCESS);
        message.Message = "Your data has been saved!";
        return PartialView("_SystemMessage", message);
    }
    catch
    {
        var message = new SystemMessage(Models.eMessageType.ERROR);
        message.Message = "Save Failed!";
        return PartialView("_SystemMessage", message);
    }
 
}
 
[ChildActionOnly]
public ActionResult FundingSources(int proposalID)
{
    var context = new PASSEntities();
 
    var model = (from a in context.Proposal_Funding_Sources
                 join b in context.Funding_Sources on a.Funding_Source_ID equals b.ID
                 where a.Proposal_ID == proposalID
                 select new FundingSourcesViewModel()
                 {
                     ID = a.ID,
                     Proposal_ID = a.Proposal_ID,
                     Funding_Source_ID = a.Funding_Source_ID,
                     Funding_Specify = a.Funding_Specify,
                     FundingSourceDescription = b.Description
                 });
 
    return PartialView(model);
}
 
[HttpPost]
[ChildActionOnly]
public ActionResult DeleteFundingSource(int id)
{
    try
    {
        using (PASSEntities context = new PASSEntities())
        {
            var fundingsource = context.Proposal_Funding_Sources.Find(id);
            context.Entry(fundingsource).State = System.Data.EntityState.Deleted;
            context.SaveChanges();
        }
 
        var message = new SystemMessage(Models.eMessageType.SUCCESS);
        message.Message = "Your data has been saved!";
        return PartialView("_SystemMessage", message);
    }
    catch
    {
        var message = new SystemMessage(Models.eMessageType.ERROR);
        message.Message = "Save Failed!";
        return PartialView("_SystemMessage", message);
    }
}

When I try to debug, the DeleteFindingSource Post method is not reached but instead the Required Post method (which is the parent view) is called.

Thanks.
Stephen
Top achievements
Rank 1
 answered on 25 Oct 2013
3 answers
362 views
Hi,

I am facing the format issues in the DateTime Picker control in the scenario if it behaves as a individual control / when it is placed inside the grid.

Please find the attached document for detailed explanation.

Regards,
Sreejesh
Alexander Popov
Telerik team
 answered on 25 Oct 2013
1 answer
394 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
268 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
339 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
149 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
112 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
776 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
112 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
Narrow your results
Selected tags
Tags
Grid
General Discussions
Scheduler
DropDownList
Chart
Editor
TreeView
DatePicker
Upload
ComboBox
MultiSelect
ListView
Window
TabStrip
Menu
Installer and VS Extensions
Spreadsheet
AutoComplete
TreeList
Gantt
PanelBar
NumericTextBox
Filter
ToolTip
Map
Diagram
Button
PivotGrid
Form
ListBox
Splitter
Application
FileManager
Sortable
Calendar
View
MaskedTextBox
PDFViewer
TextBox
Toolbar
MultiColumnComboBox
Dialog
DropDownTree
Checkbox
Slider
Switch
Notification
ListView (Mobile)
Pager
Accessibility
ColorPicker
DateRangePicker
Wizard
Security
Styling
Chat
MediaPlayer
TileLayout
DateInput
Drawer
SplitView
Template
Barcode
ButtonGroup (Mobile)
Drawer (Mobile)
ImageEditor
RadioGroup
Sparkline
Stepper
TabStrip (Mobile)
GridLayout
Badge
LinearGauge
ModalView
ResponsivePanel
TextArea
Breadcrumb
ExpansionPanel
Licensing
Rating
ScrollView
ButtonGroup
CheckBoxGroup
NavBar
ProgressBar
QRCode
RadioButton
Scroller
Timeline
TreeMap
TaskBoard
OrgChart
Captcha
ActionSheet
Signature
DateTimePicker
AppBar
BottomNavigation
Card
FloatingActionButton
Localization
MultiViewCalendar
PopOver (Mobile)
Ripple
ScrollView (Mobile)
Switch (Mobile)
PivotGridV2
FlatColorPicker
ColorPalette
DropDownButton
AIPrompt
PropertyGrid
ActionSheet (Mobile)
BulletGraph
Button (Mobile)
Collapsible
Loader
CircularGauge
SkeletonContainer
Popover
HeatMap
Avatar
ColorGradient
CircularProgressBar
SplitButton
StackLayout
TimeDurationPicker
Chip
ChipList
DockManager
ToggleButton
Sankey
OTPInput
ChartWizard
SpeechToTextButton
InlineAIPrompt
TimePicker
StockChart
RadialGauge
ContextMenu
ArcGauge
AICodingAssistant
+? more
Top users last month
Top achievements
Rank 1
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
ivory
Top achievements
Rank 1
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
YF
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Top achievements
Rank 1
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
ivory
Top achievements
Rank 1
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
YF
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?