jQuery UI Widgets › Forums › Grid › Send ajax data to action in asp.net. Pass parameters
Tagged: ajax, angular grid, asp .net mvc, callback function, data, delete row, deleterow, grid, jquery grid, jqxgrid, MVC, parameter
This topic contains 10 replies, has 2 voices, and was last updated by Dimitar 8 years, 5 months ago.
-
Author
-
Hey guys, i am almost finishing my project here.
I am trying to send data from Ajax to asp.net.
Here is my controller code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Planilhas.Models;
using Microsoft.AspNet.Identity;namespace Planilhas.Controllers
{public class Listar_DNController : Controller
{
//banco de dados da aplicação
private OurDbContext db = new OurDbContext();// GET: /Listar/
public ActionResult Index()
{
var _d = db.diluicao_normal.Include(d => d.ID).Include(d => d.cliente).Include(d => d.grupo).Include(d => d.cota).Include(d => d.contrato).Include(d => d.usuario).Include(d => d.alteracao);
return View(db.diluicao_normal.ToList());
}//GetListar()
public JsonResult GetListar(string sortdatafield, string sortOrder, int pagesize, int pagenum)
{var query = Request.QueryString;
var dbResult = db.Database.SqlQuery<diluicao_normal>(this.BuildQuery(query));
var _d = from diluicao_normal in dbResult
select new diluicao_normal
{
ID = diluicao_normal.ID,
cliente = diluicao_normal.cliente,
cota = diluicao_normal.cota,
grupo = diluicao_normal.grupo,
contrato = diluicao_normal.contrato,
usuario = diluicao_normal.usuario,
alteracao = diluicao_normal.alteracao
};
if (sortdatafield != null && sortOrder != “”)
{
_d = this.SortOrders(_d, sortdatafield, sortOrder);
}
var total = dbResult.Count();
_d = _d.Skip(pagesize * pagenum).Take(pagesize);var result = new
{
TotalRows = total,
Rows = _d
};return Json(result, JsonRequestBehavior.AllowGet);
}private IEnumerable<diluicao_normal> SortOrders(IEnumerable<diluicao_normal> collection, string sortField, string sortOrder)
{
if (sortOrder == “asc”)
{
collection = collection.OrderBy(c => c.GetType().GetProperty(sortField).GetValue(c, null));
}
else
{
collection = collection.OrderByDescending(c => c.GetType().GetProperty(sortField).GetValue(c, null));
}
return collection;
}private string BuildQuery(System.Collections.Specialized.NameValueCollection query)
{
var filtersCount = int.Parse(query.GetValues(“filterscount”)[0]);
var queryString = @”SELECT * FROM diluicao_normal “;
var tmpDataField = “”;
var tmpFilterOperator = “”;
var where = “”;
if (filtersCount > 0)
{
where = ” WHERE (“;
}
for (var i = 0; i < filtersCount; i += 1)
{
var filterValue = query.GetValues(“filtervalue” + i)[0];
var filterCondition = query.GetValues(“filtercondition” + i)[0];
var filterDataField = query.GetValues(“filterdatafield” + i)[0];
var filterOperator = query.GetValues(“filteroperator” + i)[0];
if (tmpDataField == “”)
{
tmpDataField = filterDataField;
}
else if (tmpDataField != filterDataField)
{
where += “) AND (“;
}
else if (tmpDataField == filterDataField)
{
if (tmpFilterOperator == “”)
{
where += ” AND “;
}
else
{
where += ” OR “;
}
}
// build the “WHERE” clause depending on the filter’s condition, value and datafield.
where += this.GetFilterCondition(filterCondition, filterDataField, filterValue);
if (i == filtersCount – 1)
{
where += “)”;
}
tmpFilterOperator = filterOperator;
tmpDataField = filterDataField;
}
queryString += where;
return queryString;
}private string GetFilterCondition(string filterCondition, string filterDataField, string filterValue)
{
switch (filterCondition)
{
case “NOT_EMPTY”:
case “NOT_NULL”:
return ” ” + filterDataField + ” NOT LIKE ‘” + “” + “‘”;
case “EMPTY”:
case “NULL”:
return ” ” + filterDataField + ” LIKE ‘” + “” + “‘”;
case “CONTAINS_CASE_SENSITIVE”:
return ” ” + filterDataField + ” LIKE ‘%” + filterValue + “%'” + ” COLLATE SQL_Latin1_General_CP1_CS_AS”;
case “CONTAINS”:
return ” ” + filterDataField + ” LIKE ‘%” + filterValue + “%'”;
case “DOES_NOT_CONTAIN_CASE_SENSITIVE”:
return ” ” + filterDataField + ” NOT LIKE ‘%” + filterValue + “%'” + ” COLLATE SQL_Latin1_General_CP1_CS_AS”; ;
case “DOES_NOT_CONTAIN”:
return ” ” + filterDataField + ” NOT LIKE ‘%” + filterValue + “%'”;
case “EQUAL_CASE_SENSITIVE”:
return ” ” + filterDataField + ” = ‘” + filterValue + “‘” + ” COLLATE SQL_Latin1_General_CP1_CS_AS”; ;
case “EQUAL”:
return ” ” + filterDataField + ” = ‘” + filterValue + “‘”;
case “NOT_EQUAL_CASE_SENSITIVE”:
return ” BINARY ” + filterDataField + ” <> ‘” + filterValue + “‘”;
case “NOT_EQUAL”:
return ” ” + filterDataField + ” <> ‘” + filterValue + “‘”;
case “GREATER_THAN”:
return ” ” + filterDataField + ” > ‘” + filterValue + “‘”;
case “LESS_THAN”:
return ” ” + filterDataField + ” < ‘” + filterValue + “‘”;
case “GREATER_THAN_OR_EQUAL”:
return ” ” + filterDataField + ” >= ‘” + filterValue + “‘”;
case “LESS_THAN_OR_EQUAL”:
return ” ” + filterDataField + ” <= ‘” + filterValue + “‘”;
case “STARTS_WITH_CASE_SENSITIVE”:
return ” ” + filterDataField + ” LIKE ‘” + filterValue + “%'” + ” COLLATE SQL_Latin1_General_CP1_CS_AS”; ;
case “STARTS_WITH”:
return ” ” + filterDataField + ” LIKE ‘” + filterValue + “%'”;
case “ENDS_WITH_CASE_SENSITIVE”:
return ” ” + filterDataField + ” LIKE ‘%” + filterValue + “‘” + ” COLLATE SQL_Latin1_General_CP1_CS_AS”; ;
case “ENDS_WITH”:
return ” ” + filterDataField + ” LIKE ‘%” + filterValue + “‘”;
}
return “”;
}diluicao_normal _d = new diluicao_normal();
// GET: /Employees/Create
public ActionResult Create()
{
ViewBag.ReportsTo = new SelectList(db.diluicao_normal, “ID”);
return View(_d);
}
//
// POST: /Employees/Create
[HttpPost]
public ActionResult Create(diluicao_normal _d)
{
_d.bem_taxa_no_plano = ((_d.tx_adm_total + _d.fdo_reserva) / 100) + 1;
_d.vlr_bem_mais_tax = (_d.vlr_bem * _d.bem_taxa_no_plano);
_d.taxa_real = ((_d.fdo_reserva + 7) / 100) + 1;
_d.valor_real = _d.vlr_bem * _d.taxa_real;
_d.vlr_parce_sem_seguro = _d.valor_real / _d.prazo;
_d.vlr_seguro = ((_d.vlr_bem * _d.bem_taxa_no_plano) * _d.seguro_percent) / 100;
_d.parc_sem_ad_dilu = _d.vlr_parce_sem_seguro + _d.vlr_seguro;
_d.parc_inicial = (((_d.vlr_parce_sem_seguro) / _d.bem_taxa_no_plano) / _d.vlr_bem);
_d.parcelas_restantes = ((_d.vlr_parce_sem_seguro / _d.bem_taxa_no_plano) / _d.vlr_bem);
_d.cima_per_sobre_5 = 5;
_d.per_sobre_5_parcelas_iniciais = (((_d.vlr_parce_sem_seguro – 0) / _d.bem_taxa_no_plano) / _d.vlr_bem) * 100;
_d.cima_sobre_restantes = _d.prazo – _d.cima_per_sobre_5;
_d.per_sobre_parc_restantes = ((_d.vlr_parce_sem_seguro / _d.bem_taxa_no_plano) / _d.vlr_bem) * 100;if ((_d.cima_sobre_restantes * _d.per_sobre_parc_restantes) + (_d.per_sobre_5_parcelas_iniciais * 5) > 0)
{
_d.totalizando = (_d.cima_sobre_restantes * _d.per_sobre_parc_restantes) + (_d.per_sobre_5_parcelas_iniciais * 5);
}
else
{
_d.totalizando = 0;
}_d.vlr_parc_mensal_parc_restantes = _d.vlr_parce_sem_seguro + _d.vlr_seguro;
_d.vlr_parc_mensal_iniciais = _d.vlr_parc_mensal_parc_restantes;
_d.vlr_parcela_inicial_mais_adesao = _d.vlr_parc_mensal_iniciais;
_d.valor_adm = (_d.vlr_bem * _d.tx_adm_total) / 100;
_d.f_res = (_d.vlr_bem * _d.fdo_reserva) / 100;
_d.resumo_seguro = _d.vlr_seguro * _d.prazo;
_d.resumo_total = _d.vlr_bem + _d.valor_adm + _d.f_res + _d.resumo_seguro;_d.ad_a_vista = _d.ad_a_vista;
_d.parc_inicial = _d.vlr_parc_mensal_iniciais;
_d.parcelas_restantes = _d.vlr_parce_sem_seguro + _d.vlr_seguro;_d.parc_ini_valor1 = _d.cima_per_sobre_5;
_d.parcelas_restantes_valor1 = _d.cima_sobre_restantes;
_d.ad_a_vista_valor1 = 1;_d.ad_a_vista_valor2 = _d.ad_a_vista_valor1 * _d.ad_a_vista;
_d.parc_ini_valor2 = _d.parc_ini_valor1 * _d.parc_inicial;
_d.parcelas_restantes_valor2 = _d.vlr_parc_mensal_parc_restantes * _d.parcelas_restantes_valor1;
_d.total_quadro = _d.ad_a_vista_valor2 + _d.parc_ini_valor2 + _d.parcelas_restantes_valor2;_d.lance_valor = _d.vlr_bem * _d.lance / 100;
_d.saldo_devedor = _d.total_quadro – _d.parcela_1 – _d.lance_valor;
_d._qte_meses = _d.prazo – 1;
_d.valor_qtd_meses = _d.saldo_devedor / _d._qte_meses;
if (_d.vlr_parc_mensal_parc_restantes > 0)
{
_d._j38 = Math.Round(_d.saldo_devedor – _d.vlr_parc_mensal_parc_restantes) / _d.vlr_parc_mensal_parc_restantes;}
else
{
_d._j38 = 0;
}_d._l39 = (_d.total_quadro – _d.lance_valor) / _d.prazo;
_d.alteracao = DateTime.Now;
_d.bem = _d.vlr_bem;
_d.usuario = User.Identity.GetUserName();
if (ModelState.IsValid)
{
db.diluicao_normal.Add(_d);
db.SaveChanges();
TempData[“Message”] = ” Salvo com Sucesso “;
return View(_d);
}
ViewBag.ReportsTo = new SelectList(db.diluicao_normal, “ID”, _d.ReportsTo);
return View(_d);
}// GET: /Orders/Details/5
public ViewResult Details(int id)
{
diluicao_normal _d = db.diluicao_normal.Find(id);
return View(_d);
}[HttpPost]
public ActionResult Update(diluicao_normal _d)
{
if (ModelState.IsValid)
{
db.Entry(_d).State = EntityState.Modified;
db.SaveChanges();
return Json(“true”);
}
return Json(“false”);
}public ActionResult Delete(string ID)
{var _d = db.diluicao_normal.Find(ID);
if (_d == null)
{
return HttpNotFound();
}return View(_d);
}[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(string id, bool? saveChangesError = false)
{
if (saveChangesError.GetValueOrDefault())
{
ViewBag.ErrorMessage = “Não foi possível excluir. Tente novamente ou fale com o administrador”;
}
` try
{
diluicao_normal _d = db.diluicao_normal.Find(id);
db.diluicao_normal.Remove(_d);db.SaveChanges();
}
catch (DataException/* dex */)`
{
//Log the error (uncomment dex variable name and add a line here to write a log.
return RedirectToAction(“Delete”, new { id = id, saveChangesError = true });
}
return RedirectToAction(“Index”);
}[HttpPost]
public ActionResult Add(diluicao_normal _d)
{
if (ModelState.IsValid)
{
db.diluicao_normal.Add(_d);
db.SaveChanges();
return Json(“true”);
}
return Json(“false”);
}// GET: /Employees/Edit/5
[HttpGet]
public ActionResult Edit(int ID)
{diluicao_normal _d = db.diluicao_normal.Find(ID);
ViewBag.ReportsTo = new SelectList(db.diluicao_normal, “ID”, “Cliente”, _d.ReportsTo);
return View(_d);
}
//
// POST: /Employees/Edit/5
[HttpPost]
public ActionResult Edit(diluicao_normal _d)
{
if (ModelState.IsValid)
{
db.Entry(_d).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction(“Index”);
}
ViewBag.ReportsTo = new SelectList(db.diluicao_normal, “EmployeeID”, “LastName”, _d.ReportsTo);
return View(_d);
}//// POST: /Employees/Delete/5
//[HttpPost, ActionName(“Delete”)]
//public ActionResult DeleteConfirmed(int id)
//{
// diluicao_normal _d = db.diluicao_normal.Find(id);
// db.diluicao_normal.Remove(_d);// db.SaveChanges();
// return RedirectToAction(“Index”);//}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}}
}and here is my view
@model IEnumerable<Planilhas.Models.diluicao_normal>
<h4>
@{
ViewBag.Title = “Index”;
}</h4>
@section scripts {<script type=”text/javascript” src=”http://jqwidgets.com/jquery-widgets-demo/scripts/jquery-1.11.1.min.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqx-all.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxgrid.filter.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxgrid.columnsresize.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxgrid.columnsreorder.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxgrid.edit.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxgrid.sort.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxdatetimeinput.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxcalendar.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxtooltip.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxdatetimeinput.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxmenu.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxlistbox.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxdropdownlist.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxscrollbar.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxbuttons.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxdata.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxcore.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxgrid.selection.js”></script><script type=”text/javascript” src=”../../jqwidgets/globalization/globalize.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxcalendar.js”></script><script type=”text/javascript” src=”../../jqwidgets/jqxgrid.pager.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxdatetimeinput.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxdata.js”></script>
<script type=”text/javascript” src=”../../jqwidgets/jqxdata.export.js”></script>
<script type=”text/javascript” src=”~/Scripts/LocalizationObj.js”></script>
<script type=”text/javascript” src=”~/Scripts/buttons.js”></script><link rel=”stylesheet” type=”text/css” href=”/jqwidgets/styles/jqx.base.css” />
<link rel=”stylesheet” href=”/jqwidgets/styles/jqx.energyblue.css” type=”text/css” />
<style type=”text/css”></style>
<script type=”text/javascript”>
$(document).ready(function () {var source =
{datatype: “json”,
datafields: [
{ name: ‘ID’, type: ‘number’ },
{ name: ‘cliente’, type: ‘string’ },
{ name: ‘cota’, type: ‘number’ },
{ name: ‘grupo’, type: ‘number’ },
{ name: ‘contrato’, type: ‘number’ },
{ name: ‘usuario’, type: ‘string’ },
{ name: ‘alteracao’, type: ‘date’ },],
url: ‘/Listar_DN/GetListar/’,
deleterow: $(“#deleterowbutton”).bind(‘click’, function () {
var rowindex = $(‘#jqxgrid’).jqxGrid(‘getselectedrowindex’);
var dados = $(‘#jqxgrid’).jqxGrid(‘getrowdata’, rowindex);
var rowid = dados.ID;
var ID = rowid;$.ajax({
data: JSON.stringify(ID),
dataType: ‘json’,
url: “Listar_DN/Delete/”,
contentType: “application/json; charset=utf-8”,success: function (result) {
alert(“Aeeww! Funcionou”);
},
failure: function (errMsg) {
alert(errMsg);}
})
}),addrow: function (rowid, rowdata, position, commit) {
// synchronize with the server – send insert command
$.ajax({
cache: false,
dataType: ‘json’,
url: ‘Listar_DN/Add’,
data: rowid,
type: “POST”,
success: function (data, status, xhr) {
// insert command is executed.
commit(true);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
commit(false);
}
});
},loadcomplete: $(“#updaterowbutton”).bind(‘click’, function () {
var rowindex = $(‘#jqxgrid’).jqxGrid(‘getselectedrowindex’);
var dados = $(‘#jqxgrid’).jqxGrid(‘getrowdata’, rowindex);
var rowid = dados.ID;// synchronize with the server – send update command
$.ajax({
dataType: ‘json’,
data: rowid,
type:’GET’,
url: ‘/Listar_DN/Edit/’,success: function (data) {
alert(“Hey jude”);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(“Hoje nao”);
commit(false);
}
})
}),filter: function () {
// update the grid and send a request to the server.
$(“#jqxgrid”).jqxGrid(‘updatebounddata’, ‘filter’);
},
sort: function () {
// update the grid and send a request to the server.
$(“#jqxgrid”).jqxGrid(‘updatebounddata’, ‘sort’);},
root: ‘Rows’,
beforeprocessing: function (data) {
source.totalrecords = data.TotalRows;
}};
var columnsrenderer = function (value) {
return ‘<div style=”text-align: center; margin-top: 5px;”>’ + value + ‘</div>’;
};var dataadapter = new $.jqx.dataAdapter(source, {
loadError: function (xhr, status, error) {
alert(error);
}});
//definiindo meu Grid
$(“#jqxgrid”).jqxGrid(
{
width: 1140,
source: dataadapter,
sortable: true,
filterable: true,
selectionmode: ‘singlerow’,
pageable: true,
virtualmode: true,
theme: ‘energyblue’,
//mudando o nome do meu filtro para portugues
ready: function () {
$(“#jqxgrid”).jqxGrid(‘localizestrings’, localizationobj);},
rendergridrows: function (obj) {
return obj.data;
},//colunas do meu grid
columns: [
{ text: “Id”, datafield: “ID”, cellsalign: ‘center’, cellsformat: ‘d’, width: 70, renderer: columnsrenderer, key: true },
{ text: “Cliente”, datafield: “cliente”, cellsalign: ‘center’, width: 300, renderer: columnsrenderer },
{ text: “Grupo”, datafield: “grupo”, cellsalign: ‘center’, cellsformat: ‘N’, width: 90, renderer: columnsrenderer },
{ text: “Cota”, datafield: “cota”, cellsalign: ‘center’, cellsformat: ‘N’, width: 90, renderer: columnsrenderer },
{ text: “Contrato”, datafield: “contrato”, cellsalign: ‘center’, cellsformat: ‘N’, width: 110, renderer: columnsrenderer },
{ text: “Usuario”, datafield: “usuario”, cellsalign: ‘center’, width: 120, renderer: columnsrenderer },
{
text: “Data de Alteração”, datafield: “alteracao”, cellsalign: ‘center’, width: 170, renderer: columnsrenderer, cellsformat: ‘dd/MM/yyyy HH:mm:ss’, filterable: false, filtertype: “date”, createfilterwidget: function (column, columnElement, widget) {
$(widget).jqxDateTimeInput({ formatString: ‘dd/MM/yyyy’ });
}
},{
text: “Diluicao Normal”, width: 190, renderer: columnsrenderer, filterable: false, sortable: false,
cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {defaulthtml = ‘<span class=”glyphicon glyphicon-eye-open” title=”Ver”></span> <i class=”glyphicon glyphicon-pencil” title=”Editar”></i> <i class=”glyphicon glyphicon-trash” title=”Excluir”></i>‘;
return defaulthtml;
}
}
],}
)//botoes para CRUD
// $(“#addrowbutton”).jqxButton();
$(“#deleterowbutton”).jqxButton();
//$(“#updaterowbutton”).jqxButton();});
</script>
}
<html>
<head><link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css”>
<link rel=”stylesheet” href=”~/Content/Lista.css” type=”text/css” />
</head>
@if (Request.IsAuthenticated && @ViewBag.title != “Login”)
{
<body>
<div id=”criarPla”>
<i class=”glyphicon glyphicon-plus” title=”Criar planilha”></i>
</div>
<div id=”jqxgrid” style=”font-size: 13px; font-family: Verdana; height:400px; width:1140px; background-color:white”></div>
<div style=”margin-left: 30px; float: left;”>
<div>
@*<input id=”addrowbutton” type=”button” value=”Add” />*@
<input id=”deleterowbutton” type=”button” value=”Excluir” /></div>
</div>
<div id=”pager”></div>
<div id=’grid-panel’ class=’scroll’>
<input type=”button” value=”Exportar para PDF” id=’pdfExport’ />
<input type=”button” value=”Imprimir” id=’print’ /></div>
<div style=’margin-top: 20px;’>
<div style=’float: left;’>
<div style=’margin-left: 10px; float: left;’></div>
</div>
</div></body>
}
</html>I am trying to send the ID to my action. I am implementing the deleterow.
It´s almost working. My code works like that.First i get the id of the row when i click.
After that i pass to my ajax function to send the data to my action
When i run the application i get the following error:
The id has ? before the number.
Can anyone help me with that ??
It´s suppose to open the http://localhost:34558/Listar_DN/Delete/id
Thank you guys, if you guys dont understand anything, just ask me. I will be around.
BTW, the problem is not http://localhost:34558/Listar_DN/Listar_DN/Delete/?31.
I already fixed it. Now is http://localhost:34558/Listar_DN/Delete/?31
The problem is the ? before the number 31.
Come on Guys, need your help. All the other questions in this forum have been responded.
Hello anderson_tuy,
deleterow, like addrow, is a callback function and should be set to a function, not a statement like this:
deleterow: $("#deleterowbutton").bind('click', function() { ...
Please try updating it to:
deleterow: function(rowid, commit) { var rowindex = $('#jqxgrid').jqxGrid('getselectedrowindex'); var dados = $('#jqxgrid').jqxGrid('getrowdata', rowindex); var rowid = dados.ID; var ID = rowid; $.ajax({ data: ID.toString(), dataType: 'json', url: "Listar_DN/Delete/", contentType: "application/json; charset=utf-8", success: function(result) { alert("Aeeww! Funcionou"); }, failure: function(errMsg) { alert(errMsg); } }) },
On a side note, loadcomplete is not part of the data adapter’s source objects, but of its settings object. For more information, please refer to the jqxDataAdapter help topic.
Best Regards,
DimitarjQWidgets team
http://www.jqwidgets.com/Thank you Dimitar. Now makes more sense.
How my button is gonna know that i am calling this function ??
I need the ajax to send the id to my action controller. To open the page localhost:34558/Listar_DN/Delete/15 for example. The id 15 would be the clicked row id.
I do not need to delete a row. I need to get the id and send to my action to open the delete page.
Hello anderson_tuy,
The deleterow callback should only be used for deleting rows in the back end and in the front end grid. If you wish to see a working example with it, you can take a look at our tutorial CRUD with jqxGrid, ASP.NET MVC3 and SQL.
If you wish to make a custom Ajax call to your server side, you can do so on a button click (bind to it outside the grid’s initialization code), e.g.:
$("#jqxgrid").jqxGrid({ width: 1140, source: dataadapter, sortable: true, filterable: true, selectionmode: 'singlerow', pageable: true, virtualmode: true, theme: 'energyblue', //mudando o nome do meu filtro para portugues ready: function() { $("#jqxgrid").jqxGrid('localizestrings', localizationobj); }, rendergridrows: function(obj) { return obj.data; }, //colunas do meu grid columns: [{ text: "Id", datafield: "ID", cellsalign: 'center', cellsformat: 'd', width: 70, renderer: columnsrenderer, key: true }, { text: "Cliente", datafield: "cliente", cellsalign: 'center', width: 300, renderer: columnsrenderer }, { text: "Grupo", datafield: "grupo", cellsalign: 'center', cellsformat: 'N', width: 90, renderer: columnsrenderer }, { text: "Cota", datafield: "cota", cellsalign: 'center', cellsformat: 'N', width: 90, renderer: columnsrenderer }, { text: "Contrato", datafield: "contrato", cellsalign: 'center', cellsformat: 'N', width: 110, renderer: columnsrenderer }, { text: "Usuario", datafield: "usuario", cellsalign: 'center', width: 120, renderer: columnsrenderer }, { text: "Data de Alteração", datafield: "alteracao", cellsalign: 'center', width: 170, renderer: columnsrenderer, cellsformat: 'dd/MM/yyyy HH:mm:ss', filterable: false, filtertype: "date", createfilterwidget: function(column, columnElement, widget) { $(widget).jqxDateTimeInput({ formatString: 'dd/MM/yyyy' }); } }, { text: "Diluicao Normal", width: 190, renderer: columnsrenderer, filterable: false, sortable: false, cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) { defaulthtml = '<span class="glyphicon glyphicon-eye-open" title="Ver"></span> <i class="glyphicon glyphicon-pencil" title="Editar"></i> <i class="glyphicon glyphicon-trash" title="Excluir"></i>'; return defaulthtml; } }], }) $("#deleterowbutton").bind('click', function() { var rowindex = $('#jqxgrid').jqxGrid('getselectedrowindex'); var dados = $('#jqxgrid').jqxGrid('getrowdata', rowindex); var rowid = dados.ID; var ID = rowid; $.ajax({ data: JSON.stringify(ID), dataType: 'json', url: "Listar_DN/Delete/", contentType: "application/json; charset=utf-8", success: function(result) { alert("Aeeww! Funcionou"); }, failure: function(errMsg) { alert(errMsg); } }) });
Best Regards,
DimitarjQWidgets team
http://www.jqwidgets.com/Thanks Dimitar. I am almost done here.
Now my view is like that.
$(“#deleterowbutton”).bind(‘click’, function () {
var rowindex = $(‘#jqxgrid’).jqxGrid(‘getselectedrowindex’);
var dados = $(‘#jqxgrid’).jqxGrid(‘getrowdata’, rowindex);
var rowid = dados.ID;
var id = rowid;$.ajax({
data: JSON.stringify(id),
dataType: ‘json’,
url: “/Listar_DN/Delete/”,
contentType: “application/json; charset=utf-8”,
success: function (result) {
alert = (“Deu certo”);
},
error: function () {
alert(“Nem rolou”);}
})
});$(“#deleterowbutton”).jqxButton();
And my controller like that:
[HttpGet]
public ActionResult Delete(string id)
{
if (id == null)
{
return HttpNotFound();
}var _d = db.diluicao_normal.Find(id);
if (_d == null)
{
return HttpNotFound();
}return View(_d);
}[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{try
{
diluicao_normal _d = db.diluicao_normal.Find(id);
db.diluicao_normal.Remove(_d);db.SaveChanges();
}
catch (DataException/* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
return RedirectToAction(“Delete”, new { id = id, saveChangesError = true });
}
return RedirectToAction(“Index”);
}The ajax call sends a null id to my Controller. Do u know why ??
Ajax call
Controller
Now i am trying and the Controller gets the id. The problem now is that it should redirect to page http://localhost:34558/Listar_DN/Delete/id.
But nothing happens after ajax sends the id to the controller.
Do you know why Dimitar ??
Hello anderson_tuy,
I am sorry, but we can only assist you with the client-side part of your code, which is directly related to our widget. Implementing the server code is up to you, but you can check out our help topics in the ASP .NET Integration section of the Documentation.
Best Regards,
DimitarjQWidgets team
http://www.jqwidgets.com/ -
AuthorPosts
You must be logged in to reply to this topic.