Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
530
asp.net mvc 4.0 project problems using igGrid
posted

Hi, i am currently trying to use igGrid on my project, i am using entity framework.

What i am trying to acheive is a simple delete the select rows.

So i select the rows, then the button delete becomes enable, i press it and a igDialog appear asking for confirmation.

if button ok is press the row is delete from database and the grid is refresh, if button cancel, it reloads the grid..

in this moment i am having some problems when interaction with the grid...

here is my code.. 

index.cshtml view

@model IEnumerable<LicenciamentoMVC.Models.Cliente>
@using Infragistics.Web.Mvc
@{
ViewBag.Title = "Index";
}
<script type="text/javascript">
$(function () {
$("#grid1").dblclick(function (event) {
// row html element

var row = $(event.target).closest('tr');
// data key value
var key = row.attr("data-id");
alert(key);
// cell values
var Nome = row.find('td:eq(0)').text();
alert(Nome);

// get the next cell value by changing eq index argument. For example :eq(3) will return four element
}
);
$("#addRow").igButton({ labelText: $("#addRow").val(), disabled: false });
$("#delRow").igButton({ labelText: $("#delRow").val(), disabled: true });
$("#grid1").on("iggridupdatingrowdeleted", function (e, args) {
$("#delRow").igButton("option", "disabled", false);
$("#addRow").igButton("option", "disabled", true);


});
$("#dialogButtonOk").on('click',
function (e) {

$("#grid1").igGrid("commit");
$("#grid1").igGrid("saveChanges");
$("#igDialog1").igDialog("close");
$("#grid1").igGrid("dataBind");
return false;
});
$("#dialogButtonCancel").on('click',
function (e) {



$("#igDialog1").igDialog("close");
$("#grid1").igGrid("dataBind");
return true;
});
$("#delRow").on('igbuttonclick',
function (e) {

$("#igDialog1").igDialog("open");



$(this).igButton("disable");
$("#addRow").igButton("enable");
return true;
}
);

});
</script>
@(Html
.Infragistics()
.Dialog()
.State(DialogState.Closed)
.ContentID("igDialog1")
.CloseOnEscape(true)
.HeaderText("Eliminar Registos?")
.ShowCloseButton(true)

.Width("400px")

.Render()
)

@( Html.Infragistics().Grid<LicenciamentoMVC.Models.Cliente>()
.AutoGenerateColumns(true)
.Caption("Clientes")
.ID("grid1")

.PrimaryKey("IDCliente")
.Columns(column =>
{
column.For(x => x.IDCliente).DataType("int").Hidden(true);
column.For(x => x.Nome).DataType("string").HeaderText("Nome");


})
.Features(features =>
{
features.Paging().PageSize(20).PrevPageLabelText("Previous").NextPageLabelText("NEXT");
features.Sorting().Mode(SortingMode.Single).ColumnSettings(settings =>
{
settings.ColumnSetting().ColumnKey("Nome").AllowSorting(true);

});
features.Selection().MultipleSelection(false).Mode(SelectionMode.Row);
features.Filtering().Mode(FilterMode.Simple);
features.Updating()
.EnableAddRow(false)
.EnableDeleteRow(true)
.EditMode(GridEditMode.None);


})
.DataSourceUrl(Url.Action("ListarClientes"))
.UpdateUrl(Url.Action("DeleteClientes"))
.Width("100%")

.DataBind()
.Render()
)
<input type="button" id="addRow" class="button-style" value="Criar Novo" />
<input type="button" id="delRow" class="button-style" value="Eliminar" />
<div id="igDialog1"><h1>Deseja Eliminar os registos selecionados?</h1><br />
<input type="button" id="dialogButtonOk" class="button-style" value="OK" />
<input type="button" id="dialogButtonCancel" class="button-style" value="Cancelar" />
</div>

Cliente Controller

using LicenciamentoMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Infragistics.Web.Mvc;
using System.Data.SqlTypes;

namespace LicenciamentoMVC.Controllers
{
public class ClienteController :BaseController
{
private MvcApplication1Context db = new MvcApplication1Context();
//
// GET: /Cliente/

public ActionResult Index()
{
return View();
}

//
// GET: /Cliente/Details/5

public ActionResult Details(int id)
{
return View();
}

//
// GET: /Cliente/Create

public void DeleteClientes()
{
GridModel gridModel = new GridModel();
List<Transaction<Cliente>> transactions = gridModel.LoadTransactions<Cliente>(HttpContext.Request.Form["ig_transactions"]);

foreach (Transaction<Cliente> t in transactions)
{
if (t.type == "deleterow")
{

Cliente delCliente = db.Clientes.Find(Int32.Parse(t.rowId));
delCliente.TStamp = GetDateTimeFromSqlSytem();
delCliente.Rem = 1;
db.SaveChanges();

}

}


}


[GridDataSourceAction]
public ActionResult ListarClientes()
{
return View(LicenciamentoMVC.Models.ClienteModel.GetListaClientes());
}
}
}

Model class

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace LicenciamentoMVC.Models
{
public class Cliente
{
[Key]
public int IDCliente { get; set; }

public string Nome { get; set; }
public string Morada { get; set; }
public string CPostal { get; set; }
public string Localidade { get; set; }
public string Freguesia { get; set; }
public string Conselho { get; set; }
public string Distrito { get; set; }
public string Pais { get; set; }
public string Telefone { get; set; }
public string Telemovel { get; set; }
public string Fax { get; set; }
public string Email { get; set; }
public string Nif { get; set; }

public string Observacoes { get; set; }
public int IDP { get; set; }
public int IDU { get; set; }
public DateTime TStamp { get; set; }
public int Rem { get; set; }
public String TipoCliente { get; set; }

}
public class ClienteModel
{
private static Cliente entity;
public static IQueryable<Cliente> GetListaClientes()
{
MvcApplication1Context db = new MvcApplication1Context();

var customers = from c in db.Clientes
orderby c.IDCliente descending
where c.Rem==0
select c;

return customers.AsQueryable<Cliente>();
}

// public static void DeleteCliente(int ID)
// {
// MvcApplication1Context db = new MvcApplication1Context();
// var deleteCliente =
//from c in db.Clientes where c.IDCliente == ID
//select c;

// if (deleteCliente.Count() > 0)
// {

// db.Clientes.Attach(deleteCliente);
// db.Clientes.Remove(employer);
// db.SaveChanges();
// }


// }


}
}

So when i load the grid for the first time, it load ok, i select 3 rows to be delete and i confirm my decision, what happen is that there is a post to the action with all the 3 rows and the DeleteClientes action is being call and on sql server the rows are being deleted, the way to confirm this is by check rem(Remove) field 1 is delete, 0 is normal.

After grid bind, the pager sais that only one of the tree rows were deleted,if i try the select again one of the other 2 rows it gives me error because the row doesnt exist...

When the button cancel is pressed i want to reload the grid, but this error appear

 Error: Grid has pending transactions which may affect rendering of data. To prevent exception, application may enable "autoCommit" option of igGrid, or it should process "dataDirty" event of igGridUpdating and return false. While processing that event, application also may do "commit()" data in igGrid.

Thanks in advance...

Parents
  • 3595
    Suggested Answer
    posted

    Hello,

    Thank you for posting in our community!

    A detailed sample which represents how row editing could be implemented might be found at the following resource:

    http://igniteui.com/grid/basic-editing

    There are some additional functionalities added here such as undo/redo of grid rows editing. Changes are saved by the following javascript function (see the bolded line):

                $("#saveChanges").on('igbuttonclick',

                    function (e) {

                        grid.igGrid("saveChanges");

                        $("#undo").igButton("disable");

                        $(this).igButton("disable");

                        return false;

                    }

                );

     

    Then the controller method defined in the grid .UpdateUrl() setting is automatically invoked and the update transactions are processed like that:

    public ActionResult OrdersSaveData()

            {

                GridModel gridModel = new GridModel();

                List<Transaction<Order>> transactions = gridModel.LoadTransactions<Order>(HttpContext.Request.Form["ig_transactions"]);

                var orders = RepositoryFactory.GetOrderRepository();

                foreach (Transaction<Order> t in transactions)

                {

                    …

                       

                  

                }

     

                JsonResult result = new JsonResult();

                Dictionary<string, bool> response = new Dictionary<string, bool>();

                response.Add("Success", true);

                result.Data = response;

                return result;

            }

     

    It is not needed to handle manually events triggered by pressing the “Done” or “Cancel” buttons. The igGrid("saveChanges")method automatically send the transactions to the controller.

    Hope this helps. If you need any further assistance feel free to update this forum thread.

Reply Children
No Data