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

Inline Edit and Update with ViewModel

1 Answer 546 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Allan
Top achievements
Rank 1
Allan asked on 29 Mar 2016, 04:11 PM

Hello,

I have a kendo grid in my MVC application.  I have a viewmodel that shows related data in the grid, when the user edits a row using inline editing I need it to update the database via the viewmodel.  How is this done?

My grid code

@(Html.Kendo().Grid<Multiple_Table_Post.ViewModels.MultiPostViewModel>()
          .Name("Grid")
          .Columns(columns =>
              {
                  columns.Bound(c => c.id).Title("ID");
                  columns.Bound(c => c.parent_id).Title("PID");
                  columns.Bound(c => c.vessel_name).Title("Name")
                  .ClientTemplate("<a href='" + Url.Action("Details", "Vessels") + "/#=parent_id#'" + ">#=vessel_name#</a>");
                  columns.Bound(c => c.vessel_location).Title("Location");
                  columns.Bound(c => c.vessel_mmsi).Title("MMSI");
                  columns.Bound(c => c.vessel_bhp).Title("BHP");
                  columns.Bound(c => c.vessel_omid).Title("OMID");
                  columns.Command(command =>
                  {
                      command.Edit()
                          .Text("Edit")
                          .UpdateText("Update")
                          .CancelText("Cancel");
                  }).Width(110);
              }
          )
          .Pageable()
          .Editable(editable => editable.Mode(GridEditMode.InLine))          
          .DataSource(dataSource => dataSource
              .Ajax()
              .PageSize(7)
              .Read(read => read.Action("data_read", "InlineEdit"))
              .Update(update => update.Action("data_update", "InlineEdit"))
              .Sort(sort => sort.Add("id").Descending())
              .Model(model =>
              {
                  model.Id(p => p.id);
              })
               
               
          )
      )

The viewmodel

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Multiple_Table_Post.Models;
 
namespace Multiple_Table_Post.ViewModels
{
    public class MultiPostViewModel
    {
        // #Vessel
        public int id { get; set; }
 
        [Display(Name = "Name [Vessels(table)]")]
        [Required(ErrorMessage = "Vessel name cannot be left blank")]
        public string vessel_name { get; set; }
 
        [Required(ErrorMessage = "Location cannot be left blank")]
        [Display(Name = "Location [Vessels(table)]")]
        [UIHint("LocationEditor")]
        public string vessel_location { get; set; }
 
        [Display(Name = "MMSI [Vessels(table)]")]
        public string vessel_mmsi { get; set; }
         
        // #Vessel Details
        // Without primary key ID.
        [Display(Name = "OMID [Vessels Details(table)]")]
 
        public Nullable<System.DateTime> vessel_omid { get; set; }
 
        [Display(Name = "BHP [Vessels Details(table)]")]
        [Required(ErrorMessage = "BHP cannot be left blank")]
        public Nullable<decimal> vessel_bhp { get; set; }      
 
        [Display(Name = "PID [Vessels Details(table)]")]
        public Nullable<int> parent_id { get; set; }
 
        [Display(Name = "DECK [Vessels Details(table)]")]
        public Nullable<decimal> vessel_deck { get; set; }
         
        public virtual ICollection<vessel_details> vessel_details { get; set; }
    }
}

Controll 

public ActionResult data_read([DataSourceRequest]DataSourceRequest request)
       {
           var datacontext = db.vessel_details.AsQueryable();
 
           IQueryable<MultiPostViewModel> thevessel = from c in datacontext
                                                      select new MultiPostViewModel
                                                      {
                                                          id = c.id,
                                                          parent_id = c.vessel.id,
                                                          vessel_name = c.vessel.vessel_name,
                                                          vessel_location = c.vessel.vessel_location,
                                                          vessel_mmsi = c.vessel.vessel_mmsi,
                                                          vessel_omid = c.vessel_omid,
                                                          vessel_bhp = c.vessel_bhp,
 
                                                      };
 
           DataSourceResult result = thevessel.ToDataSourceResult(request);
 
           return Json(result);
       }

Controller : UPDATE Grid Data

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult data_update([DataSourceRequest]DataSourceRequest request, VesselsViewModel vessel)
{
    if (ModelState.IsValid)
    {
        var entity = new vessel();
        entity.id = vessel.id;
        entity.vessel_name = vessel.vessel_name;
        entity.vessel_location = vessel.vessel_location;
        entity.vessel_mmsi = vessel.vessel_mmsi;               
         
  
    db.vessels.Attach(entity);
    db.Entry(entity).State=EntityState.Modified;
    db.SaveChanges();
    }
 
    return Json(new[] { vessel }.ToDataSourceResult(request, ModelState));
}
The update code is where I am stuck, how can I get this code to use my view model and update the related tables??  Anyone ever had this problem?

 

Thanks

 

1 Answer, 1 is accepted

Sort by
0
Dimiter Topalov
Telerik team
answered on 31 Mar 2016, 01:32 PM
Hello Allan,

The exact implementation depends on your data base access services, but in general, you have to perform similar to the following steps in your update action:

1) Check ModelState ( if(this.ModelState.IsValid)... )

2) Obtain the currently edited object from the data base, e.g.:

var vesselToUpdate = db.vessels.GetById(vessel.Id);
if(vesselToUpdate == null)... // return some error/notification
...

3) Update vesselToEdit's properties to match the one that come with the request:
...
vesselToUpdate.vessel_name = vessel.vessel_name;
vesselToUpdate.vessel_location = vessel.vessel_location;
...

4) Persist the changes to the data base (this may vary depending on the data base access pattern in use):
db.vessels.Attach(vesselToUpdate);
db.Entry(vesselToUpdate).State=EntityState.Modified;
db.SaveChanges();

5) Return the vessel along with information about the request and the ModelState in acceptable for the DataSource format

You can check out the following demo both online and offline in your demos for MVC, coming with your UI for ASP.NET MVC installation package:

http://demos.telerik.com/aspnet-mvc/grid/editing-inline

http://docs.telerik.com/kendo-ui/aspnet-mvc/introduction

I hope this helps.

Regards,
Dimiter Topalov
Telerik
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Tags
Grid
Asked by
Allan
Top achievements
Rank 1
Answers by
Dimiter Topalov
Telerik team
Share this question
or