This is a migrated thread and some comments may be shown as answers.

[Solved] Batch editing relationship problem

1 Answer 118 Views
Grid
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Garðar Valur
Top achievements
Rank 1
Garðar Valur asked on 03 Oct 2011, 06:52 PM
Hi!  :)
I´m having problem with displaying batch-editable-grid when I add more than one table into my sql entity.  I´m using Linq-to-SQL and started out with a small test project to use multiple features for the grid in Telerik for MVC.  I started out with only one table in the database and got the batch-editable-grid working perfectly.  Then I wanted to test out the feature of adding dropdownlist to my grid an therefore adding another table to my database entity (with a foreign key between those tables).  I wanted to add the dropdownlist for the new table which should be a fairly simple thing.  When I add the new table to the Linq entity (dbml) and create foreign key constrain between those two tables, run the project again, I loose all the data from the grid.  Here´s an example from my view (i´m using Razor):

@using Telerik.Web.Mvc.UI
@using TelerikGridTest.Models
@(Html.Telerik().Grid<Employee>()
        .Name("Grid")
        .DataKeys(keys =>
                      {
                          keys.Add(p => p.EmployeeID).RouteKey("EmployeeID");
                      })
        .ToolBar(commands => {
            commands.Insert().ButtonType(GridButtonType.Image);
            commands.SubmitChanges().ButtonType(GridButtonType.Image);
                             })
        .DataBinding(dataBinding =>
            dataBinding.Ajax()
                .Select("SelectBatchEditing", "Employee")
                .Update("SaveBatchEditing", "Employee")
        )
        .Columns(columns =>
        {
            columns.Bound(p => p.EmployeeID).Title("Númer");
            columns.Bound(p => p.Title).Title("Nafn");
            columns.Bound(p => p.Age).Title("Aldur");
            columns.Bound(p => p.Email).Title("Netfang");
            columns.Command(commands => commands.Delete().ButtonType(GridButtonType.Image)).Title("Eyða");
        })
        .ClientEvents(events => events.OnDataBinding("Grid_onDataBinding").OnError("Grid_onError"))
        .Editable(editing => editing.Mode(GridEditMode.InCell).DefaultDataItem(new Employee()))
        .Pageable()
        .Scrollable()
        .Sortable()
        )
 
<script type="text/javascript">
    function Grid_onError(args) {
        if (args.textStatus == "modelstateerror" && args.modelState) {
            var message = "Errors:\n";
            $.each(args.modelState, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            args.preventDefault();
            alert(message);
        }
    }
    function Grid_onDataBinding(e) {
        var grid = $(this).data('tGrid');
        if (grid.hasChanges()) {
            if (!confirm('You are going to lose any unsaved changes. Are you sure?')) {
                e.preventDefault();
            }
        }
    }
</script>

The thing is that I have been debugging this and everything seems to be fine until the controller returns the data to the view-page.  I was wondering if I should be adding another Datakey to the grid (Datakey for the new table)?  Should I bind columns differently?

This is my controller:

using System.Collections.Generic;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using TelerikGridTest.Models;
 
namespace TelerikGridTest.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult EditingBatch()
        {
            return View();
        }
        [GridAction]
        public ActionResult SelectBatchEditing()
        {
            return View(new GridModel(EmployeeRepository.All()));
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult SaveBatchEditing(
            [Bind(Prefix = "inserted")]IEnumerable<Employee> insertedEmployee,
            [Bind(Prefix = "updated")]IEnumerable<Employee> updatedEmployee,
            [Bind(Prefix = "deleted")]IEnumerable<Employee> deletedEmployee)
        {
            if (insertedEmployee != null)
            {
                foreach (var employee in insertedEmployee)
                {
                    EmployeeRepository.Insert(employee);
                }
            }
            if (updatedEmployee != null)
            {
                foreach (var employee in updatedEmployee)
                {
                    var target = EmployeeRepository.One(p => p.EmployeeID == employee.EmployeeID);
                    if (target != null)
                    {
                        target.EmployeeID = employee.EmployeeID;
                        target.Title = employee.Title;
                        target.Age = employee.Age;
                        target.Email = employee.Email;
                        EmployeeRepository.Update(target);
                    }
                }
            }
            if (deletedEmployee != null)
            {
                foreach (var product in deletedEmployee)
                {
                    EmployeeRepository.Delete(product);
                }
            }
            return View(new GridModel(EmployeeRepository.All()));
        }
    }
}


And this is my Repository model:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace TelerikGridTest.Models
{
    public class EmployeeRepository
    {
        private static readonly WorkersDataContext _db = new WorkersDataContext();
 
        public static IList<Employee> All()
        {
            IList<Employee> result = (IList<Employee>)HttpContext.Current.Session["Products"];
            if (result == null)
            {
                HttpContext.Current.Session["Products"] = result = (from empl in _db.Employees
                                                                    select empl).ToList();}
            return result;
        }
        public static Employee One(Func<Employee, bool> predicate)
        {
            return All().Where(predicate).FirstOrDefault();
        }
        public static void Insert(Employee employee)
        {
            employee.EmployeeID = All().OrderByDescending(p => p.EmployeeID).First().EmployeeID + 1;
            All().Insert(0, employee);
        }
        public static void Update(Employee employee)
        {
            Employee target = One(p => p.EmployeeID == employee.EmployeeID);
            if (target != null)
            {
                target.EmployeeID = employee.EmployeeID;
                target.Title = employee.Title;
                target.Age = employee.Age;
                target.Email = employee.Email;
            }
        }
        public static void Delete(Employee employee)
        {
            Employee target = One(p => p.EmployeeID == employee.EmployeeID);
            if (target != null)
            {
                All().Remove(target);
            }
        }
 
 
    }
}

I´m sorry for dumping all the code in here but I´m desperate for any help!

Any help is greatly appreciated  :)

Best regards,
Garðar Valur Hallfreðsson

1 Answer, 1 is accepted

Sort by
0
Garðar Valur
Top achievements
Rank 1
answered on 04 Oct 2011, 01:10 PM
Update!

I opened my dbml file and removed the relation between the two tables (see attachment).  Once I did that everything worked fine and I got my Employee data populated into the grid. 

I was wondering how to use foreign key constrains like I described above?  (I haven´t found any solution yet, please help)!  :)

Regards,
Garðar
Tags
Grid
Asked by
Garðar Valur
Top achievements
Rank 1
Answers by
Garðar Valur
Top achievements
Rank 1
Share this question
or