Bind Webgrid using JQuery failed - javascript

Hi I am using webgrid this time.and Binding json data using JQuery. My ajax call script providing data but I am unable to get it some how.I have gone thorugh all the questions available here but nothing worked. Look at the components and tell me what is wrong.
This is the web grid
<div id="GridContent">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 15, selectionFieldName: "Id", ajaxUpdateContainerId: "GridContent", canSort: true);
}
#grid.GetHtml(
tableStyle: "webgrid-table",
rowStyle: "webgrid-row-style",
htmlAttributes:"grid",
emptyRowCellValue: "--",
headerStyle: "webgrid-header",
selectedRowStyle: "webgrid-alternating-row",
columns: grid.Columns(
grid.Column(columnName: "CenterId", header: "Id"),
grid.Column(columnName: "CenterName", header: "CenterName"),
grid.Column(columnName: "CenterCode", header: "CenterCode"),
grid.Column(columnName: "Address", header: "Address"),
grid.Column(columnName: "EmailId", header: "EmailId"),
grid.Column(format: #<a id="EditCenter" class="fa-anchor" data-id="#item.CenterId">Edit</a>),
grid.Column(format: (item) => Html.ActionLink((string)"Delete", "DeleteCenter", new { CenterId = item.CenterId }, new { id = "DeleteCenter", onclick = "return confirm('Are You Sure Want To Delete The Center Data?');" }))))
</div>
and here is my ajax call for binding the data on dropdown change.
$(document).ready(function () {
$("#ListType").change(function () {
var webgrid;
$.ajax({
type: 'POST',
url: ListTypeUrl,
data: { id: $("#ListType").val() },
datatype:'html',
success: function (result) {
$("#GridContent").html(result);
alert("Success");
},
error: function (result) {
alert("On select Failed " + result);
}
});
})
});
Here is Controller method for getting JSON Results
public JsonResult GetCenterList(int id)
{
List<CenterDetails> cd = objDal.GetCenterListItem(id.ToString(), Session["AgentId"].ToString());
return Json(cd,JsonRequestBehavior.AllowGet);
}
public List<CenterDetails> GetCenterListItem(string type, string AgentId)
{
XElement xl = new XElement("root"
, new XAttribute("OType", "Select")
, new XAttribute("Target", "CenterList")
, new XElement("Type",Convert.ToInt32(type))
, new XElement("AgentId", AgentId));
ds = ExecuteDataSet("Sp_CenterAction", CommandType.StoredProcedure, new MySqlParameter("#xml", xl.ToString()));
dt = ds.Tables[0];
drc = dt.Rows;
List<CenterDetails> objList = new List<CenterDetails>();
foreach (DataRow dr in drc)
{
objList.Add(new CenterDetails
{
CenterId = Convert.ToInt32(dr["cm_Id"].ToString()),
CenterName = dr["cm_Name"].ToString(),
CenterCode = dr["cm_CenterCode"].ToString(),
Address = dr["cm_Address"].ToString(),
EmailId = dr["cm_EmailId"].ToString()
});
}
return objList;
}

Related

Unable to append params dynamically to the API using angular datatables

Trying to load datatable with few records initially and once datatable loaded, trying to click pagination buttons, here trying like if we click on pagination button need to reload the API with latest with updated params and load set of records instead of all records at a time. Developed below code for pagination for huge data,
loadTable() {
this.dtOptions = {
processing: true,
destroy: true,
pagingType: 'full_numbers',
pageLength: 10,
columns: [
{ title: '<input type="checkbox" />' },
{ data: 'index' },
{ data: 'firstname' },
{ data: 'lastname' }
],
infoCallback: (oSettings, iStart, iEnd, iMax, iTotal, sPre) => {
pageStartNo = iStart;
pageEndNo = iEnd;
console.log(pageStartNo, pageEndNo);
params = new HttpParams()
.set('param1', '111')
.set('param2', '222')
.set('minNumber', pageStartNo)
.set('maxNumber', pageEndNo);
console.log('params >>>>>>>>>>>>>' + params.toString());
}
};
this.http
.get<any[]>(
'https://angular-datatables-demo-server.herokuapp.com/',
{
params
}
)
.subscribe(response => {
this.persons = response.data;
this.dtTrigger.next();
});
}
Stackblitz

How to Update the params for every pagination button clicks

Trying to implement pagination, Initially I'm trying to load datatable with few records, once page loaded trying to click pagination buttons like next or any pagination buttons to update the new set of records. I'm able to get the iStart, iEnd records but unable to update the url for every pagination click. Trying to print the console but function is not calling and console.log is not updated with new params. Could you please suggest me how to do the update the params for API. Here is the sample code,
Sample Demo datatatble is not work with pagination, for verification printing the console for the updated querystring.
ngOnInit(): void {
this.dtOptions = {
processing: true,
destroy: true,
columns: [
{ title: '<input type="checkbox" />' },
{ data: 'index' },
{ data: 'firstname' },
{ data: 'lastname' }
],
infoCallback: (oSettings, iStart, iEnd, iMax, iTotal, sPre) => {
pageStartNo = iStart;
pageEndNo = iEnd;
console.log(pageStartNo, pageEndNo);
// this.loadTable();
}
};
}
loadTable(){
let params = new HttpParams()
.set('param1', '123')
.set('param2', '456')
.set('minNumber', pageStartNo)
.set('maxNumber', pageEndNo);
console.log('params >>>>>>>>>>>>>' + params.toString());
this.http
.get<any[]>(
'https://raw.githubusercontent.com/l-lin/angular-datatables/master/demo/src/data/data.json',
{
params
}
)
.subscribe(response => {
this.persons = response.data;
this.dtTrigger.next();
});
}
HTML code:
<button (click)="loadTable()">Load Table</button>
Sample Demo Stackblitz
If I understand your question correctly, you wanted to apply server-side pagination right?
Here is an official documentation for this.
Add ajax method in dtOptions.
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 10,
serverSide: true,
processing: true,
ajax: (dataTablesParameters: any, callback) => {
console.log('Params', dataTablesParameters);
//If you have different key for page number/size change it
dataTablesParameters.minNumber = dataTablesParameters.start + 1;
dataTablesParameters.maxNumber =
dataTablesParameters.start + dataTablesParameters.length; this.http
.post<any[]>(
'YOUR_API_NAME_HERE',
dataTablesParameters,
{}
)
.subscribe(resp => {
this.persons = resp.data;
//Once API fetched data successfully inform datatable by invoking the callback
callback({
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: []
});
});
},
columns: [{ data: 'id' }, { data: 'firstName' }, { data: 'lastName' }]
};
Working Stackbliz Demo

Fetching events on FullCalendar

I'm trying to make FullCalendar works on my app, but I'm not able to fetch the events I have on my mysql database. Here is my code:
.cshtml
<div class="panel-body">
<script type="text/javascript">
$(document).ready(function () {
$('#calendar').fullCalendar({
height: 600,
width: 500,
theme: false,
fixedWeekCount: false,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay',
},
weekends: false,
editable: false,
eventSources: [
'Agenda/getEvents'
],
});
});
</script>
<div id="calendar"></div>
</div>
.cs controller
{
public class AgendaController : Controller
{
// GET: Agenda
public ActionResult Index()
{
return View();
}
public ActionResult Agenda()
{
ViewBag.id = Session["id"];
ViewBag.usuario = Session["usuario"];
ViewBag.tipo_usuario = Session["tipo_usuario"];
return View();
}
[HttpPost]
public JsonResult getEvents(double start, double end)
{
try
{
DataTable dt = new DataTable();
using (MySqlConnection con = new MySqlConnection(BD.CadConMySQL()))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT tareas.tipo as title, tareas.fecha_inicio as start, tareas.fecha_fin as end FROM tareas", con))
{
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
return Json(dt.ToList());
}
catch (Exception e)
{
RespGeneric resp = new RespGeneric("KO");
resp.msg = e.Message;
return Json(resp);
}
}
So the Agenda/getEvents give me back this following JSON that seems ok for FullCalendar:
JSON
However, the calendar doesnt show any event and I dont get why because the JSON looks good and if I fetch the events one by one on the .cshtml with exactly the same data it works.
Thanks!
I think that you didn't respect the structure of a standard eventSource fetch which is described in the documentation as :
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
url: '/myfeed.php',
type: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});

Updating server from Kendo Color picker inside kendo grid

The Problem
So i am currently trying to implement a color picker inside of a Kendo grid, that will hopefully send the chosen color to my Sql Table. Unfortunately, It doesn't seem as though the Update controller is being reached. I am relatively new to Kendo UI, so there might be some incredibly dumb errors shown.
Questions
I guess my main question would be: How can i call the update method when update is clicked on the grid. Essentially, the color picker and the edit command are showing up in beautiful fashion. I just want to know how i can be sure that the method is being called when 'Update' is clicked, seeing as it is not reaching my controller. Feel free to ask if you need to see more code or perhaps a screen shot.
Code
Config.cshtml ( Grid )
#model IEnumerable<STZN.Models.AGCData.ErrorCode>
#{
ViewBag.Title = "Config";
}
#section HeadContent{
<script src="~/Scripts/common.js"></script>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
editable: "inline",
selectable: "row",
dataSource: {
schema: {
model: {
id: "error_code",
fields: {
color: { type: 'string' }
}
}
},
transport: {
read: {
type: "POST",
dataType: "json",
url: "#Url.Action("ErrorCodes")"
},
update: {
type: "POST" ,
dataType: "json",
url: "#Url.Action("UpdateErrorCodes")",
}
}
},
columns: [
{ command : [ "edit" ] },
{
field: "error_code", title: "Error Code",
},
{
field: "error_description", title: "Error Description"
},
{
field: "color",
width: 150,
title: "Color",
template: function (dataItem) {
return "<div style = 'background-color: " + dataItem.color + ";' </div>"
},
editor: function (container, options) {
var input = $("<input/>");
input.attr("color",options.field);
input.appendTo(container);
input.kendoColorPicker({
value: options.model.color,
buttons: false
})
},
}
]
});
});
</script>
}
Update Controller
public JsonResult UpdateErrorCodes(ErrorCode model)
{
using (var db = new AgcDBEntities())
{
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
db.Configuration.ProxyCreationEnabled = false;
var data = db.ErrorCodes.Where(d => d.error_code == model.error_code).Select(x => new
{
error_code = x.error_code,
description = x.error_description,
color = x.color,
});
return new JsonResult()
{
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
};
}
}
I actually managed to fix my issue by adding an additional input attribute to my editor function in the "color" field. It looks like this:
input.attr("data-bind","value:" + options.field);
There are still some present issues (unrelated to the fix/server update) , but as far as updating to the server, It work's as intended.

Jquery function cannot fire event from new data in webgrid

Wasn't exactly sure how to title this problem, but essentially what my issue is, is calling a jquery function based on a new elements that gets put into my WebGrid. However, my webgrid is populated on toggling of radio buttons. The grid then gets updated with new data by an ajax call. Therefore, no page refresh is done and my elements exist in my grid, but my javascript does not know about them.
Below is some of my code.
Webgrid:
#grid.GetHtml(tableStyle: "table table-striped table-bordered",
headerStyle: "thead-default",
columns: grid.Columns(
grid.Column("account_number", "Account Number", canSort: true),
grid.Column("last_name", "Last Name", canSort: true),
grid.Column("first_name", "First Name", canSort: true),
grid.Column("middle_name", "Middle Name", canSort: true),
grid.Column("reject_reviewed", "Reviewed", canSort: true, format: (item) => Html.CheckBox("completed", (bool)(item.reject_reviewed == 1), new { disabled = "disabled" })),
grid.Column("comment", "Comments", format: (item) =>
new HtmlString(
Html.ActionLink("Add", "RejectAddComment", controller, new RejectCommentViewModel { reject_id = item.id, account_number = item.account_number, reject_message = item.reject_message },
htmlAttributes: new { data_modal = "", id = "btnCreate", #class = "" }).ToString()
+ " | " +
Html.ActionLink("View", "RejectViewComment", controller, new RejectCommentViewModel { reject_id = item.id, account_number = item.account_number, reject_message = item.reject_message },
htmlAttributes: new { data_modal = "", id = "btnCreate", #class = "" }).ToString())),
grid.Column("reject_message", "Reject Message", canSort: true)))
javascript:
$(function () {
$.ajaxSetup({ cache: false });
$("body").on("click", 'a[data-modal]', function (e) {
// hide dropdown if any
$(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
/*backdrop: 'static',*/
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
//Refresh
location.reload();
} else {
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
Change your event binding from:
$("a[data-modal]").on("click", function (e) {
To
$("body").on("click", 'a[data-modal]',function (e) {
and it is better to use a a better selector than body, something like you grid id or class
By the way this is a famous issue, googled
Changed the line to this
$("#scroll-grid").on("click", "#btnCreate", function (e)
and the javascript event now fires.
The first element must be a parent element, and after the click event must be the element you are looking for the event of.

Categories