Telerik Forums
UI for ASP.NET MVC Forum
1 answer
103 views
Hi,

I have a simple grid with only the Read and Destroy actions defined for the datasource. I also have an error event handler defined. While playing around with this setup, I noticed, that the row is removed as soon as I click the destroy button, even before the controller is called. If an error occures in the controller, my error handler does, what it should, but the grid is not refreshed. Do I have to do that by myself (If so, how do i do this in the error handler?) or did I make a mistake?

My View:
@(Html.Kendo().Grid<StorageClasses>()
            .Name("StorageClassesGrid")
            .ToolBar(toolbar => toolbar.Template("<button id='btnAddSC' class='k-button'><span class='k-icon k-add'></span></button>"))
            .Columns(columns =>
            {
                columns.Command(command =>
                {
                    command.Destroy().Text(" ").HtmlAttributes(new { style = "width:14px;min-width:27px" });
                }).Width("40px;");
                columns.Bound(p => p.Name);
                columns.Bound(p => p.Remark);
            })
                .Pageable(pager => pager.Refresh(true))
                .Sortable()
                .Scrollable(s => s.Height("auto"))
                .Filterable()
                .Resizable(r => r.Columns(true))
                .DataSource(dataSource => dataSource
                    .Ajax()
                    .ServerOperation(false)
                    .Model(model => model.Id(m => m.ID))
                    .Read(read => read.Action("GetStorageClassesByLocation", "Locations", new { LocationID = Model.ID }))
                    .Destroy(destroy => destroy.Action("StorageClass_Delete", "Locations", new { LocationID = Model.ID }))
                    .Events(e => e.Error("onGridError"))
                )
                .Events(e => e.Remove("onGridRowRemove").DataBound("resizeTabs"))
            )

Controller:
[HttpPost]
        public ActionResult StorageClass_Delete([DataSourceRequest] DataSourceRequest request, long? LocationID, StorageClasses StorageClass)
        {
            Exception exception;
 
            if (StorageClass != null && LocationID != null)
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        // delete entity in database
                        var result = _db.StorageClass_Delete(
                                    LocationID.HasValue ? LocationID.Value : 0,
                                    StorageClass.ID,
                                    ClientName,
                                    "WEB",
                                    UserName,
                                    out exception);
 
                        if (exception != null)
                        {
                            AddException(exception);
                        }
 
                        // check database action result
                        if (result != null && result.ErrorID == 0)
                        {
                            // database action successful
                            return Json(new[] { StorageClass }.ToDataSourceResult(request, ModelState));
                        }
                        else
                        {
                            ModelState.AddModelError("StorageClass_Delete", result.ErrorMessage);
                            return Json(new[] { StorageClass }.ToDataSourceResult(request, ModelState));
                        }
                    }
                }
                catch (Exception ex)
                {
                    AddException(ex);
                    ModelState.AddModelError("StorageClass_Delete", ex.Message);
                    return Json(new[] { StorageClass }.ToDataSourceResult(request, ModelState));                   
                }
            }
            ModelState.AddModelError("StorageClass_Delete", "Parameter Fehler.");
            return Json(new[] { StorageClass }.ToDataSourceResult(request, ModelState));
        }

Error Handler:
function onGridError(e) {
        var txt = "";
 
        $.each(e.errors, function (propertyName) {
            txt = txt +this.errors + " ";
        });
 
        $("#lblStatus").text(txt);
        $("#lblStatus").css('color', 'red', 'font-weight ', 'bold');
    }

Best regards

Dietmar
Alexander Popov
Telerik team
 answered on 05 Dec 2013
1 answer
259 views
Hello ,i m using Kendo grid with pop-up edit mode.I have created custom template page for pop-up window.On this template there are some comboboxes.
I want user that can input(on combo's textarea)  only from combobox's value.

E.g.:

Combobox-Values: red,yellow,green

When user fill the combobox's textarea like "RED" or "Yellow" validator message should appears and ,update button should return false such required = "required"
does on combobox.

@(Html.Kendo().ComboBox()<br>
            .Name("IDTYPE")<br>
                                    //.AutoBind(false)<br>
                         //.Events(e => e<br>
                         //               .Change("combobox_select"))<br>
                    .DataTextField("DESCRIPTION").HtmlAttributes(new { style = "width:220px", required = "required" })<br>
            .DataValueField("REFERENCEID")<br>
                                    //   .Value(Model.IDTYPEGUID.ToString()) // Initial value<br>
                                    //  .BindTo(Model.IDTYPE) <br>
                                    //.AutoBind(true)   <br>
                     .Placeholder("SELECT")<br>
<br>
                        .DataSource(source =><br>
                        {<br>
                            source.Read(read =><br>
                            {<br>
<br>
                                read.Action("GetDefinitionDetails", "Definition", new { definitionCode = "IDTYPE", addEmptyRow = false })<br>
                                    //  .Data("onAdditionalData")<br>
                                ;<br>
<br>
                            })<br>
              .ServerFiltering(true);<br>
<br>
                        }))
Alexander Popov
Telerik team
 answered on 05 Dec 2013
1 answer
86 views
HI All
          Im having a kendo MVC grid. Where say there are three columns A,B,C. Now i need to update the value of the B column on edit of A column.On Edit of A . B should be autmatically calculated and updated on UI. Ex B=A-45 .. Please help me how do i achieve this.

Regards
VIPUL
Kunal
Top achievements
Rank 1
 answered on 05 Dec 2013
1 answer
431 views
Hi,

I'm using a TreeView like in this  example. It is located in the left pane of a two pane splitter, if that matters. All events fire as they should, except the DataBound one. I already tried to modify the example code, that comes with kendo. It does not work here, too.

My TreeView code:
@(Html.Kendo().TreeView()
    .Name("MyTreeView")
    .BindTo(Model, mappings => mappings.For<TreeViewNode>(binding => binding
        .ItemDataBound((item, node) =>
            {
                item.Text = node.Name;
                item.Id = node.Value.ToString();
                item.Expanded = ViewData[ViewBag.ExpandedCookie] != null &&
                                ((string[])ViewData[ViewBag.ExpandedCookie]).Contains(item.Id);
 
                //item.HtmlAttributes["data-selectable"] = node.Selectable;
 
                if (node.AddOnly)
                    item.HtmlAttributes["data-addOnly"] = true;
                else
                    item.HtmlAttributes["data-addOnly"] = false;
 
                if (!node.Selectable)
                {
                    item.HtmlAttributes["style"] = "color: #888";
                }
                else
                    item.HtmlAttributes["style"] = "color: black";
            })
        .Children(parent => parent.Childs))).HtmlAttributes(new { @class = "k-group" }).Events(e => e
            .Select("onSelect")
            .Expand("updateTreeViewState")
            .Collapse("updateTreeViewState")
            .DragStart("onNodeDragStart")
            .DataBound("onTreeDataBound")
            .Drop("onNodeDrop")).DragAndDrop(true)
    )

And the javascript code:
function onTreeDataBound(e) {
    alert("databound");
}
 
// select event as an example (this works)
function onSelect(e) {
    var dataItem = this.dataItem(e.node);
    $("#ID").val(dataItem.id);
 
    if ($(e.item).attr("data-selectable") == "0" || dataItem.id == "0")
        e.preventDefault();
    else
        // request server for partial view for details and refresh right pane of splitter
        getSplitter("#outerSplitter").ajaxRequest("#right-pane", "/" + getArea() + "/" + getController() + "/Details", { id: dataItem.id });
 
    // update statusbar to default
    $("#lblStatus").text("Ready");
    $("#lblStatus").css('color', 'black', 'font-weight ', 'normal')
    //}
}
Am I missing something here?

Best Regards

Dietmar
Vladimir Iliev
Telerik team
 answered on 05 Dec 2013
1 answer
640 views
I am using Kendo Grid for Edit,Update,Delete user Informations.

I want to use different templates for edit and create opetation.
Currently:

.TemplateName("EditPerson"))

With this  i created a  view file(name is EditPerson.cshtml) under "EditorTemplates" folder.
i want to use another template for Create Operations.How can i do it?
Dimiter Madjarov
Telerik team
 answered on 04 Dec 2013
4 answers
341 views
Hi,

I just watched the keynote to the new release Q3/2013. While there are many cool features, I am a little underwhelmed by what was presented regarding adaptiveness of the grid.

What I expected: I thought there would be a feature that allows me to dynamically (depending on the screen size) add or remove columns shown in the grid. That's rather a usecase for me than soemone showing the grid on a mobile.

Are there solutions for this? I think there were announced at some point in time, not long ago...

Thanks,
Volker

Edit: Here is the link to the blog post I had in mind: 
http://www.kendoui.com/blogs/teamblog/posts/13-10-10/building-an-adaptive-grid-and-scheduler-for-kendo-ui.aspx
Volker
Top achievements
Rank 1
 answered on 04 Dec 2013
1 answer
308 views
I updated to latest Kendo today and now get this error.
"a directory with this name was not found"
I have had this error in the past, but cant remember how to fix it. 
I have looked at permissions and have checked the paths but all looks ok. any ideas, thanks
Alan Mosley
Top achievements
Rank 1
 answered on 03 Dec 2013
4 answers
256 views
So I have a grid that is populated from EF5
@model IEnumerable<HCS.Model.FinancialInstitution>
@(Html.Kendo().Grid(Model)
                .Name("Grid")
                .Columns(columns =>
                {
                    columns.Bound(p => p.ID).Visible(false);
                    columns.Bound(p => p.MainRT).Title("RT").Groupable(false);
                    columns.Bound(p => p.LegalName).Title("FI Name");
                })
                .Sortable()
                .Scrollable()
                .Filterable()
                .Selectable()                              
                .DataSource(dataSource => dataSource
                            .Ajax()
                            .ServerOperation(false))
                             
)
I recently added a new table to the database that has a FK to the FinancialInstitution table
I updated the model and the association and navigation are now present.

However, now I get the following error:

"A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.FinancialInstitution_1..."
 
I have found a few articles suggesting the disabling of proxy creation, but this doesn't seem to help.
public ActionResult Grid()
        {
            context.Configuration.ProxyCreationEnabled = false;
            var model = context.FinancialInstitutions.ToList();
            return View();
        }
 I also found a blog that suggests a workaround however, I am confused as to whether or not I will have to do something every time a call is made to EF to rewire the JSON results
Bob
Top achievements
Rank 1
 answered on 03 Dec 2013
1 answer
123 views
I have a grid that  I am displaying and I am trying 2 different methods....  The jquery version works and displays the data in the grid...

In Fiddler, I can see the return JSON and everything looks as it should in the browser 

 var url = "/memo/a/8/b/1";  // build URL to API

            var dataSource = new kendo.data.DataSource({    // create datasource
                transport: {
                    read: {
                        url: url,
                        dataType: "json",
                    }
                }
            });

When I try the same call using Razor (my preferred way), this will not display any data in the grid.   I see in Fiddler the exact same return JSON as as the Jquery method above.  But no data is being displayed.   Any suggestions?

@(Html.Kendo().Grid<eWJB.Models.MemoModel>()
    .Name("grid1")
    .Columns(columns =>
        {
            columns.Bound(p => p.MemoID);
            columns.Bound(p => p.Subject).Width(100).Title("Subject");
            columns.Bound(p => p.Initials).Width(30).Title("Initials");

    })
    .DataSource(dataSource => dataSource
        .Ajax()
       .Read(read => read.Url(Url.RouteUrl("GetAllMemos",  new {httproute ="", controller="Memo", branch=1, id=8 })).Type(HttpVerbs.Get))
         )
    .Sortable()
    .Scrollable()
    
)
Vladimir Iliev
Telerik team
 answered on 03 Dec 2013
2 answers
898 views
I'm at a lost. I've attempted to run my "Batch editing" grid with MVC3 and I keep receiving this error:
 "A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.aspnet_Users_8928C46E971F379B4E2E99263A0AD4EE44DD31017D7C2242241BF00A73BA81B3'."

 I've read other forums such as :

http://stackoverflow.com/questions/12845016/kendo-ui-invalidoperationexception-a-circular-reference-was-detected-while-se
http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/faq#how-do-i-avoid-circular-reference-exceptions?

I understand I can't reference a circular reference from my model in the controller or view, which I'm not and I keep receiving this error. 

I'm also using Linq with the model first approach, but I do use a metadata model to add attributes to the models fields. 
Here is some of my code.

CaseController.cs
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CustomerService.Models;
using System.Web.Security;
using System.Security.Principal;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
 
namespace CustomerService.Controllers
{
    [Authorize]
    public class CaseController : Controller
    {
        private ERPEntities db = new ERPEntities();
 
        public ActionResult Cases_Read([DataSourceRequest]DataSourceRequest request)
        {
                IQueryable<CaseHeader> cases = db.CaseHeaders;
                DataSourceResult result = cases.ToDataSourceResult(request);
                return Json(result, JsonRequestBehavior.AllowGet);
        }
 
        public ActionResult Cases_Create([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<CaseHeader> cases)
        {
            // Will keep the inserted entitites here. Used to return the result later.
            var entities = new List<CaseHeader>();
            if (ModelState.IsValid)
            {
                foreach (var x in cases)
                {
                    // Create a new Product entity and set its properties from the posted ProductViewModel
                    var entity = new CaseHeader
                    {
                        CaseHeaderId = x.CaseHeaderId,
                        Creator = x.Creator,
                        CreatedDate = x.CreatedDate,
                        CaseLead = x.CaseLead,
                        CaseSubType1 = x.CaseSubType1,
                        CaseSubType2 = x.CaseSubType2,
                        CaseStatus = x.CaseStatus,
                        CaseTitle = x.CaseTitle,
                        CaseDescription = x.CaseDescription,
                        CaseContact = x.CaseContact
                    };
                    // Add the entity
                    db.CaseHeaders.Add(entity);
                    // Store the entity for later use
                    entities.Add(entity);
                }
                // Insert the entities in the database
                db.SaveChanges();
                 
            }
            // Return the inserted entities. The grid needs the generated ProductID. Also return any validation errors.
            return Json(entities.ToDataSourceResult(request, ModelState, x => new CaseHeader
            {
                CaseHeaderId = x.CaseHeaderId,
                Creator = x.Creator,
                CreatedDate = x.CreatedDate,
                CaseLead = x.CaseLead,
                CaseSubType1 = x.CaseSubType1,
                CaseSubType2 = x.CaseSubType2,
                CaseStatus = x.CaseStatus,
                CaseTitle = x.CaseTitle,
                CaseDescription = x.CaseDescription,
                CaseContact = x.CaseContact
            }));
        }
 
        public ActionResult Cases_Update([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<CaseHeader> cases)
        {
            // Will keep the updated entitites here. Used to return the result later.
            var entities = new List<CaseHeader>();
            if (ModelState.IsValid)
            {
                foreach (var x in cases)
                {
                    // Create a new Product entity and set its properties from the posted ProductViewModel
                    var entity = new CaseHeader
                    {
                        CaseHeaderId = x.CaseHeaderId,
                        Creator = x.Creator,
                        CreatedDate = x.CreatedDate,
                        CaseLead = x.CaseLead,
                        CaseSubType1 = x.CaseSubType1,
                        CaseSubType2 = x.CaseSubType2,
                        CaseStatus = x.CaseStatus,
                        CaseTitle = x.CaseTitle,
                        CaseDescription = x.CaseDescription,
                        CaseContact = x.CaseContact
                    };
                    // Store the entity for later use
                    entities.Add(entity);
                    // Attach the entity
                    db.CaseHeaders.Attach(entity);
                    // Change its state to Modified so Entity Framework can update the existing product instead of creating a new one
                    db.Entry(entity).State = EntityState.Modified;
                    // Or use ObjectStateManager if using a previous version of Entity Framework
                    // northwind.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
                }
                // Update the entities in the database
                db.SaveChanges();
            }
            // Return the updated entities. Also return any validation errors.
            return Json(entities.ToDataSourceResult(request, ModelState, x => new CaseHeader
            {
                CaseHeaderId = x.CaseHeaderId,
                Creator = x.Creator,
                CreatedDate = x.CreatedDate,
                CaseLead = x.CaseLead,
                CaseSubType1 = x.CaseSubType1,
                CaseSubType2 = x.CaseSubType2,
                CaseStatus = x.CaseStatus,
                CaseTitle = x.CaseTitle,
                CaseDescription = x.CaseDescription,
                CaseContact = x.CaseContact
            }));
        }
 
        public ActionResult Cases_Destroy([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<CaseHeader> cases)
        {
            // Will keep the destroyed entitites here. Used to return the result later.
            var entities = new List<CaseHeader>();
            if (ModelState.IsValid)
            {
                foreach (var x in cases)
                {
                    // Create a new Product entity and set its properties from the posted ProductViewModel
                    var entity = new CaseHeader
                    {
                        CaseHeaderId = x.CaseHeaderId,
                        Creator = x.Creator,
                        CreatedDate = x.CreatedDate,
                        CaseLead = x.CaseLead,
                        CaseSubType1 = x.CaseSubType1,
                        CaseSubType2 = x.CaseSubType2,
                        CaseStatus = x.CaseStatus,
                        CaseTitle = x.CaseTitle,
                        CaseDescription = x.CaseDescription,
                        CaseContact = x.CaseContact
                    };
                    // Store the entity for later use
                    entities.Add(entity);
                    // Attach the entity
                    db.CaseHeaders.Attach(entity);
                    // Delete the entity
                    db.CaseHeaders.Remove(entity);
                    // Or use DeleteObject if using a previous versoin of Entity Framework
                    // northwind.Products.DeleteObject(entity);
                }
                // Delete the entity in the database
                db.SaveChanges();
            }
            // Return the destroyed entities. Also return any validation errors.
            return Json(entities.ToDataSourceResult(request, ModelState, x => new CaseHeader
            {
                CaseHeaderId = x.CaseHeaderId,
                Creator = x.Creator,
                CreatedDate = x.CreatedDate,
                CaseLead = x.CaseLead,
                CaseSubType1 = x.CaseSubType1,
                CaseSubType2 = x.CaseSubType2,
                CaseStatus = x.CaseStatus,
                CaseTitle = x.CaseTitle,
                CaseDescription = x.CaseDescription,
                CaseContact = x.CaseContact
            }));
        }
    }
}

Index.cshtml

@model IEnumerable<CustomerService.Models.CaseHeader>
 
@{
    ViewBag.Title = "Index";
}
 
<h2>Your Cases</h2>
 
 
@(Html.Kendo().Grid<CustomerService.Models.CaseHeader>()
      .Name("grid")
      .Columns(columns =>
      {
          columns.Bound(x => x.CaseHeaderId);
          columns.Bound(x => x.Creator);
          columns.Bound(x => x.CreatedDate);
          columns.Bound(x => x.CaseLead);
          columns.Bound(x => x.CaseType);
          columns.Bound(x => x.CaseSubType1);
          columns.Bound(x => x.CaseSubType2);
          columns.Bound(x => x.CaseStatus);
          columns.Bound(x => x.CaseTitle);
          columns.Bound(x => x.CaseDescription);
          columns.Bound(x => x.CaseContact);
          columns.Command(commands =>
          {
              commands.Destroy(); // The "destroy" command removes data items
          }).Title("Commands").Width(200);
      })
      .ToolBar(toolbar =>
      {
          toolbar.Create(); // The "create" command adds new data items
          toolbar.Save(); // The "save" command saves the changed data items
      })
      .Editable(editable => editable.Mode(GridEditMode.InCell)) // Use in-cell editing mode
      .DataSource(dataSource =>
          dataSource.Ajax()
            .Batch(true) // Enable batch updates
            .Model(model =>
            {
                model.Id(x => x.CaseHeaderId); // Specify the property which is the unique identifier of the model
                model.Field(x => x.CaseHeaderId).Editable(false); // Make the CaseHeaderId property not editable
                model.Field(x => x.CreatedDate).Editable(false);
            })
            .Create(create => create.Action("Cases_Create", "Case")) // Action method invoked when the user saves a new data item
            .Read(read => read.Action("Cases_Read", "Case"))  // Action method invoked when the grid needs data
            .Update(update => update.Action("Cases_Update", "Case"))  // Action method invoked when the user saves an updated data item
            .Destroy(destroy => destroy.Action("Cases_Destroy", "Case")) // Action method invoked when the user removes a data item
      )
      .Pageable()
)

CaseHeader.cs  
using System;
using System.Collections.Generic;
 
namespace CustomerService.Models
{
    public partial class CaseHeader
    {
        public CaseHeader()
        {
            this.Notes = new HashSet<Note>();
        }
     
        public System.Guid CaseHeaderId { get; set; }
        public System.Guid UserId { get; set; }
        public string Creator { get; set; }
        public Nullable<System.DateTime> CreatedDate { get; set; }
        public string CaseLead { get; set; }
        public string CaseType { get; set; }
        public string CaseSubType1 { get; set; }
        public string CaseSubType2 { get; set; }
        public string CaseStatus { get; set; }
        public string CaseTitle { get; set; }
        public string CaseDescription { get; set; }
        public string CaseContact { get; set; }
     
        public virtual aspnet_Users aspnet_Users { get; set; }
        public virtual ICollection<Note> Notes { get; set; }
    }
     
}
Metadata for this model (I'm not really sure if this matters but I'm not sure) - ValidateModels.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
 
namespace CustomerService.Models
{
    [MetadataType(typeof(CaseHeaderMetaData))]
    public partial class CaseHeader
    {
    }
 
    public class CaseHeaderMetaData
    {
        public System.Guid CaseHeaderId { get; set; }
        public System.Guid UserId { get; set; }
        [MaxLength(50, ErrorMessage = "Too Long!")]
        public string Creator { get; set; }
        public Nullable<System.DateTime> CreatedDate { get; set; }
        public string CaseLead { get; set; }
        public string CaseType { get; set; }
        public string CaseSubType1 { get; set; }
        public string CaseSubType2 { get; set; }
        public string CaseStatus { get; set; }
        public string CaseTitle { get; set; }
        public string CaseDescription { get; set; }
        public string CaseContact { get; set; }
 
        public virtual aspnet_Users aspnet_Users { get; set; }
        public virtual ICollection<Note> Notes { get; set; }
    }
 
    [MetadataType(typeof(UserProfileMetaData))]
    public partial class UserProfile
    {
    }
 
    public class UserProfileMetaData
    {
        public System.Guid UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [Display(Name = "Request Company")]
        public string Company { get; set; }
        public string CompanyNumber { get; set; }
 
        public virtual aspnet_Users aspnet_Users { get; set; }
    }
     
}
Any thoughts or ideas about how to fix this problem are greatly appreciated.
Thanks
 
Atanas Korchev
Telerik team
 answered on 03 Dec 2013
Narrow your results
Selected tags
Tags
+? 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?