Get Kendo Grid checkbox status on custom command - asp.net

I have a kendo grid with 4 checkbox columns with checked and unchecked status.
Now I want to updated tabel based on checkbox checked status on custom command button click.
Here is my kendo grid binding code
$(document).ready((function () {
$.ajax({
type: "POST",
url: "member-security-list.aspx/getStatus",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#grid").kendoGrid({
dataSource: {data: response.d,pageSize: 20},
sortable: {mode: "single",allowUnsort: false},
pageable: {buttonCount: 5},
scrollable: false,
columns: [
{ field: "login", title: "Login Id" },
{ field: "name", title: "Member Name" },
{ field: "mobile", title: "Mobile No." },
{ field: "Alert Status", template: "<input type='checkbox' value='oncredit' class='oncredit' #if(oncredit === '1'){#= checked='checked' #}else{}#= />On Credit <input type='checkbox' value='ondebit' class='ondebit' #if(ondebit === '1'){#= checked='checked' #}else{}#= />On Debit <input type='checkbox' value='onlogin' class='onlogin' #if(onlogin === '1'){#= checked='checked' #}else{}#= />On Login <input type='checkbox' value='isblock' class='isblock' #if(isblock === '1'){#= checked='checked' #}else{}#= />Block SMS Recharge" },
{ command: { text: "Set", click: showDetails }, title: "Set" }
]
});
},
failure: function (response) {
alert(response.d);
}
});
}));
and here is my command button click code
function showDetails(e) {
e.preventDefault();
var d = this.dataItem($(e.currentTarget).closest("tr"));
//I want to access checkbox here and find its checked status for pass parameter.
$.ajax({
type: "POST", url: "member-security-list.aspx/setAlert",
data: '{ "id":"' + d.id + '","status":"' + d.status + '"}',
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (response) {
//some other
},
failure: function (response) { }
});
}

Now I have solved my problem. Here is my working code
function showDetails(e) {
e.preventDefault();
var credit, debit, login, block;
var d = this.dataItem($(e.currentTarget).closest("tr"));
var tr = $(e.target).closest("tr");
if (tr.find('.oncredit').is(':checked'))
credit = '1';
else
credit = '0';
if (tr.find('.ondebit').is(':checked'))
debit = '1'
else
debit = '0';
if (tr.find('.onlogin').is(':checked'))
login = '1';
else
login = '0';
if (tr.find('.isblock').is(':checked'))
block = '1'
else
block = '0';
$.ajax({
type: "POST", url: "member-security-list.aspx/setAlert",
data: '{ "id":"' + d.id + '","oncredit":"' + credit + '","ondebit":"' + debit + '","onlogin":"' + login + '","isblock":"' + block + '"}',
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (response) {
alert('Updated');
},
failure: function (response) { }
});
}

Related

How to fix the INSERT statement conflicted with the foreign key constraint when I call ajax

I use ajax to create new Color (id, name) and Size (id, name) and I get their id, quantity in a row to Quantities table but checking database, they do not appear and get error.
I got size, color data when I call ajax but when I check SQL Server, it does not have their id.
$("#btnSaveQuantity").on('click', function () {
var quantityList = [];
$.each($('#table-quantity-content').find('tr'), function (i, item) {
var size = $(item).find('input.txtSize').first().val();
var color = $(item).find('input.txtColor').first().val();
addColor(color);
addSize(size);
var _color;
var _size;
$.ajax({
url: '/admin/Product/GetSize',
data: {
Name: size,
},
async: false,
type: 'get',
dataType: 'json',
success: function (data) {
console.log(data);
_color = data;
},
error: function () {
osm.notify('Has an error', 'error');
}
});
$.ajax({
url: '/admin/Product/GetColor',
data: {
Name: color,
},
type: 'get',
async: false,
dataType: 'json',
success: function (data) {
console.log(data);
_size = data;
},
error: function () {
osm.notify('Has an error', 'error');
}
});
quantityList.push({
Id: $(item).data('id'),
ProductId: $('#hidId').val(),
Quantity: $(item).find('input.txtQuantity').first().val(),
SizeId: _size.Id,
ColorId: _color.Id,
});
});
$.ajax({
url: '/admin/Product/SaveQuantities',
data: {
productId: $('#hidId').val(),
quantities: quantityList
},
async: false,
type: 'post',
dataType: 'json',
success: function (response) {
$('#modal-quantity-management').modal('hide');
$('#table-quantity-content').html('');
}
});
});
function addColor(color) {
$.ajax({
url: '/admin/Product/AddColor',
data: {
Name: color,
},
type: 'post',
dataType: 'json',
error: function () {
osm.notify('Has an error', 'error');
}
});
}
function addSize(size) {
$.ajax({
url: '/admin/Product/AddSize',
data: {
Name: size,
},
type: 'post',
dataType: 'json',
error: function () {
osm.notify('Has an error', 'error');
}
});
}
I expect that database already had recognized colorId and sizeId before I add a new quantity but actually it does not.

Is there a way to disable cache on FullCalendar?

I'm using FullCalendar on asp.net application. I noticed that when FullCalendar receives data from SQL Server via Web-Method > JSON, it creates a cache file (EventList.json) inside browser history/temporary folder.
I have cache:false on every method but I don't know how to apply the same thing on events: calendar.asmx/EventList .
Please refer to my other post that shows how I receive my data via web-method.
So my questions are:
Is there a way to disable cache on events?
How can I use ajax like other methods to get data, because with this method I can disable cache
function runCalendar() {
var $modal = $('#event-modal');
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* Initialize the calendar */
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var form = '';
var today = new Date($.now());
var calendar = $('#calendar').fullCalendar({
slotDuration: '00:15:00',
/* If we want to split day time each 15minutes */
minTime: '08:00:00',
maxTime: '20:00:00',
timeFormat: 'HH(:mm)',
defaultView: 'agendaWeek',
events: "calendar.asmx/EventList",
lazyFetching: false,
allDaySlot: false,
firstDay: 1,
//weekends: false,
handleWindowResize: true,
//columnFormat:'ddd / DD',
selectHelper: true,
height: $(window).height() - 200,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
eventLimit: true, // allow "more" link when too many events
drop: function(date) {
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
var $categoryClass = $(this).attr('data-class');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
if ($categoryClass) copiedEventObject['className'] = [$categoryClass];
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
},
selectable: true,
eventClick: function(calEvent, jsEvent, view) {
var form = $("<form></form>");
form.append("<label>Change event name</label>");
form.append("<div class='input-group'><input class='form-control' type=text value='" + calEvent.title + "' /><span class='input-group-btn'><button type='submit' class='btn btn-success'><i class='fa fa-check'></i> Save</button></span></div>");
$modal.modal({
backdrop: 'static'
});
$modal.find('.delete-event').show().end().find('.save-event').hide().end().find('.modal-body').empty().prepend(form).end().find('.delete-event').unbind('click').click(function() {
calendar.fullCalendar('removeEvents', function(ev) {
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/DeleteCalendarEvent",
dataType: "json",
data: "{'id':'" + calEvent._id + "'}",
});
return (ev._id == calEvent._id);
});
$modal.modal('hide');
});
$modal.find('form').on('submit', function() {
calEvent.title = form.find("input[type=text]").val();
calendar.fullCalendar('updateEvent', calEvent);
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/UpdateCalendarEvent",
dataType: "json",
data: "{'id':'" + calEvent._id + "','title':'" + calEvent.title + "'}",
});
$modal.modal('hide');
return false;
});
},
eventDrop: function(event, ui, jsEvent) {
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/MoveEvents",
dataType: "json",
data: "{'id':'" + event._id + "','start':'" + moment(event.start).format("DD MMMM YYYY HH:mm:ss") + "','end':'" + moment(event.end).format("DD MMMM YYYY HH:mm:ss") + "','allDay':'" + event.allDay + "'}",
});
},
eventResize: function(event, allDay) {
var allDay = !event.start.hasTime() && !event.end.hasTime();
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/ResizeEvents",
dataType: "json",
data: "{'id':'" + event._id + "','end':'" + event.end.format("DD MMMM YYYY HH:mm:ss") + "','allDay':'" + event.allDay + "'}",
});
},
select: function(start, end, allDay) {
$modal.modal({
backdrop: 'static'
});
form = $("<form></form>");
form.append("<div class='row'></div>");
form.find(".row")
.append("<div class='col-md-6'><div class='form-group'><label class='control-label'>Event Name</label><input class='form-control' placeholder='Insert Event Name' type='text' name='title'/></div></div>")
.append("<div class='col-md-6'><div class='form-group'><label class='control-label'>Category</label><select class='form-control' name='category'></select></div></div>")
.find("select[name='category']")
.append("<option value='busy'>Busy</option>")
.append("<option value='e1'>E1</option>")
.append("<option value='e2'>E2</option>")
.append("<option value='bg-blue'>Lunch</option>")
.append("<option value='bg-yellow'>Children</option></div></div>");
inputSelect();
$modal.find('.delete-event').hide().end().find('.save-event').show().end().find('.modal-body').empty().prepend(form).end().find('.save-event').unbind('click').click(function() {
form.submit();
});
$modal.find('form').on('submit', function() {
title = form.find("input[name='title']").val();
beginning = form.find("input[name='beginning']").val();
ending = form.find("input[name='ending']").val();
$categoryClass = form.find("select[name='category'] option:checked").val();
var allDay = !start.hasTime() && !end.hasTime();
if (title !== null && title.length != 0) {
//calendar.fullCalendar('renderEvent', {
// title: title,
// start:start,
// end: end,
// allDay: false,
// className: $categoryClass
//}, true);
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/CreateCalendarEvent",
dataType: "json",
data: "{'title':'" + title + "','start':'" + start.format("DD MMMM YYYY HH:mm:ss") + "','end':'" + end.format("DD MMMM YYYY HH:mm:ss") + "','category':'" + $categoryClass + "','allDay':'" + allDay + "'}",
success: function(data) {
var obj = data.d;
if (obj == 'true') {
//$('#txtFirstName').val('');
//$('#txtLastName').val('');
//$('#txtCity').val('');
//$('#txtEmailID').val('');
//$('#lblmsg').html('Data Inserted Successfully');
}
},
error: function(result) {
alert(result);
}
});
calendar.fullCalendar('refetchEvents')
$modal.modal('hide');
} else {
alert('You have to give a title to your event');
}
return false;
});
calendar.fullCalendar('unselect');
}
});
/* Creation of new category */
$('.save-category').on('click', function() {
formCategory = $('#add-category form');
var categoryName = formCategory.find("input[name='category-name']").val();
var categoryColor = formCategory.find("select[name='category-color']").val();
if (categoryName !== null && categoryName.length != 0) {
$('#external-events').append('<div class="external-event bg-' + categoryColor + '" data-class="bg-' + categoryColor + '" style="position: relative;"><i class="fa fa-move"></i>' + categoryName + '</div>')
runCalendar();
}
});
}
$(function() {
runCalendar();
});
Instead of:
events: "calendar.asmx/EventList",
following method can disable the cache
eventSources: [{
url: 'calendar.asmx/EventList',
type: 'POST',
cache: false
}],
According to FullCalendar documentation your call already prevents the browser from caching, and the fact that FullCalendar is a jQuery plugin means that under the hood it probably uses jQuery's $.ajax() method to retrieve the data.
In my case I had to turn off both lazyFetching and events cache:
eventSources: [
{
url: ...,
cache: false,
}
],
lazyFetching: false

ASP.NET and jQuery Remote Validation: Validation function not called

I have this client function:
$(document).ready(function() {
var validate = $("#<%=Page.Form.ClientID%>").validate({
errorElement: 'span',
rules: {
<%=txtMemberShipNumber.ClientID %> : {
required: true,
remote: function () {
return {
url: "/TestForm.aspx/IsMembershipNumberValid",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ value: $('#<%=txtMemberShipNumber.ClientID %>').val() }),
dataFilter: function (data) {
var msg = JSON.parse(data);
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
}
},
},
},
messages: {
<%=txtMemberShipNumber.ClientID %> : {
required: "Account number is Required",
remote: "Invalid",
},
},
onkeyup:false,
onblur: true,
onfocusout: function (element) { $(element).valid() }
});
})
... that validates this control:
<input name="ctl00$MainContent$txtMemberShipNumber" type="text" id="MainContent_txtMemberShipNumber" class="textboxStyle" placeholder="Membership Number" />
The problem is the validation code is never called. I've tested it in Firefox and Chrome.
Am I missing something?
I figured it out.
Instead of
<%=txtMemberShipNumber.ClientID %> : {
... you should use
<%=txtMemberShipNumber.UniqueID%> : {

why autocomplete textbox textchange event not firing?

I have a textbox with ajax jquery autocomplete feature.but the textchange event is not firing.
<asp:TextBox ID="txtNumber" runat="server" width="98%" OnTextChanged="txtNumber_TextChanged" AutoPostBack="true" ></asp:TextBox>
Autocomplete function:
function QuoteNumber(sender, args) {
$(function () {
$("#<%=txtNumber.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Webservice.asmx/GetNumberForAutocomplete") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
async: false,
mustMatch: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('^')[0],
val: item.split('^')[1]
}
}))
},
error: function (response) {
},
failure: function (response) {
}
});
},
select: function (e, i) {
$("#<%=hdnNumber.ClientID %>").val(i.item.val);
if (i.item.val == "No Records Found") {
$("#<%=hdnNumber.ClientID %>").val(-1);
document.getElementById('<%=txtNumber.ClientID%>').value = "";
return false;
}
},
minLength: 0
}).bind('focus', function () { $(this).autocomplete("search"); });
});
}
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtSearch.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Service.asmx/GetCustomers") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfCustomerId.ClientID %>").val(i.item.val);
$("#<%=hfCustomerName.ClientID %>").val(i.item.value);
$("[id*=btnSubmit]").click();
},
minLength: 1
});
});
Add to end of select callback this line: __doPostBack('<%= txtNumber.UniqueID %>', '');
In addition to above answer we need to below code snippest in Select:
select: function (e, i) {
$("#<%=hfCustomerId.ClientID %>").val(i.item.val);
$("#<%=hfCustomerName.ClientID %>").val(i.item.value);
$("[id*=btnSubmit]").click();
$("#<%=txtNumber.ClientID %>").val(i.item.value);
__doPostBack('<%= txtNumber.UniqueID %>', '');
},

send ajax form to web service, only after successful validation

my target is to create form that validated in the client side, and only when it is valid, send ajax call to asmx web service. i manage to do that two separately: client-side validation and ajax send to web service, and i want to combine this two. how?..
i have this form (i simplify everything for simple example):
<form id="ContactForm" runat="server">
<label for="name">Full Name</label>
<input type="text" name="name" id="name"/>
<input id="submit" type="button" />
</form>
the client validation looks like:
$(document).ready(function() {
$("#submit").click(function() {
var validator = $("#ContactForm").validate({
rules: { name: { required: true } },
messages: { name: errName }
}).form();
});
});
and the ajax send looks like this:
$(document).ready(function() {
$("#submit").click(function() {
var myMailerRequest = {name: $('#name').val()};
var data = JSON.stringify({req: myMailerRequest});
$.ajax
({
type: "POST",
url: "ContactFormMailer.asmx/SendContactForm",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
AjaxSucceeded(msg);
}, error: AjaxFailed
});
});
});
Thanks!
You can use the submitHandler option of .valdiate() for this, it only executes when a valid form is submitted (it has an invalidHandler for the opposite), like this:
$(function() {
$("#submit").click(function() {
var validator = $("#ContactForm").validate({
rules: { name: { required: true } },
messages: { name: errName },
submitHandler: function() {
var myMailerRequest = {name: $('#name').val()};
var data = JSON.stringify({req: myMailerRequest});
$.ajax({
type: "POST",
url: "ContactFormMailer.asmx/SendContactForm",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
}
}).form();
});
});
Since you're not using this though, it might be much more readable in 2 functions, like this:
$(function() {
$("#submit").click(function() {
var validator = $("#ContactForm").validate({
rules: { name: { required: true } },
messages: { name: errName },
submitHandler: ajaxSubmit
}).form();
});
function ajaxSubmit() {
var myMailerRequest = {name: $('#name').val()};
var data = JSON.stringify({req: myMailerRequest});
$.ajax({
type: "POST",
url: "ContactFormMailer.asmx/SendContactForm",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
}
});
The only other change was shortening your call to AjaxSuceeded (maybe this can't be done, only because of your simplified example), but other than that...just submit the form from the submitHandler callback and you're all set.

Resources