I have a javascript function to clear my form which includes a gridview, I previously tried another way to delete the rows without postback but somehow when I tried to add a new row, all the previous bounce back. Maybe I am using viewstate to maintain my gridview, not too sure but below is what I am doing which works well but somehow it only deletes one row, I guess probably when the postback occurs, the loop got wiped out. Any advice? I need the loop to delete all my gridview rows. Thanks!
for (i = 0; i < camGv.rows.length; i++) {
window.__doPostBack('ctl00$cphBody$gvCamVoucher', 'Delete$0');
}
Well i think you need 2 things
1- A Way to Delete Your Rows from the Grid in the Client Side
2- A way to make that deletion effect on the server side just in case you made any postbacks
to stay in your deletion state
1- you can catch the grid view in the client side with id and clear the all inside its execpt if there is a footer that have the paging like this code
document.getElementById('grid view id').getElementsByTagName('TBODY').innerHTML='';
this line of script deletes all your rows thats if you dont have a footer grid pager
2- you have to make an ajax call to contact with the server and make the real effect if that table is have some thing from the database i think u need a delete function to delete all the rows from the database , if that is just a temp table have nothing to do from the database so i suggest to put it inside a Session that you can access the session in the ajax call
JavaScript
$.ajax({
type: "POST",
//web method path
url: "pageName.aspx/webmethodName",
data: "{action:'delete'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(result)
{
}
,error: function(error)
{
}
});
ASP.NET CS
[WebMethod]
public string DeleteAll(string action)
{
//you have to put the table from the begining where ever you initialize the data on it inside a session
DataTable dt = (DataTable)HttpContext.Current.Session["tbl"];
dt.Rows.Clear();
HttpContext.Current.Session["tbl"]=dt;
}
Regards
please any question ask me :)
Thanks for the answer, I clear the gridview rows from code behind and use an Update Panel to group the grid so that the postback do not in any way affect my other fields.
Related
Hi I'm working with djangorestframework-datatables and datatables' JQuery plugin.
I'm loading a large table (about 15000 entries, paginated) with the serverSide option enabled. I enabled this option because client side processing was taking too long to load the table (even with deferLoading).
I want to retrieve data from the following URL:
/api/device_input/?format=datatables&device_id=something
// device_id can be 1, 2, 3 and so on.
The problem is, I can't figure out how I can dynamically change the device_id parameter. That parameter is definitely user input. Here's how I was previously doing it (with client side processing):
1) User enters device ID into a form. Form gets submitted.
2) Django view takes the POST request and returns the filtered queryset to the template.
3) The queryset populates the HTML table values and datatables handles the rest (pagination etc)
But now with server side processing, I don't need the django view to return any querysets. I can just get data through ajax. The behaviour I want is:
1) User opens page, an empty datatable is displayed, with a prompt to enter device ID.
2) User enters device ID, and the datatable is loaded with records for that device id.
But the datatables ajax request only gets invoked when someone messes with the datatable (such as change page or select page length). I want to invoke the ajax request when someone enters device_id into my form and dynamically tell ajax to create the right URL.
Here's what my javascript looks like:
<!-- Javascript function to initialize the datatable -->
<script>
var device_id = document.getElementById("id_input").value
$(document).ready(function() {
$("#device_inputs_table").DataTable({
"lengthMenu": [
[10, 20, 30, -1],
[10, 20, 30, "All"]
],
fixedHeader: {
headerOffset: 62
},
"order": [
[0, "desc"]
],
"serverSide": true,
"ajax": "/api/device_input/?format=datatables&device_id=" + device_id, // need to add a number at the end that user will input
"columns": [
// All my table columns
]
});
});
</script>
I'm sure this is simple to do, but my unfamiliarity with ajax and javascript has me scratching my head, any help is appreciated!
UPDATE: I tried adding a simple variable to get device_id from the form element, but it doesn't get added to my URL... how do I print my URL out on the dom? (I'm only checking through the network tab on chrome dev tools...) Of course my form doesn't even invoke the ajax request so that's another issue.
First you need to declare a variable to hold the DataTable and call it from your javascript.
Example:
var deviceInputsTable = $('#device_inputs_table').DataTable({
// Rest of the table declaration goes here.
})
Then, you create a function that triggers to load data in your deviceInputsTable, something like:
function loadDeviceInputsTableData(deviceID){
device_id = deviceID // (get this from the input)
// do the ajax call here and this is the important part:
success: function(data){
// This is just a rough scratch, but this is how you initially call the first data in the table, consequent calls will now be server-side since your device_id now has a value in the ajax call you showed above.
deviceInputsTable.clear().rows.add(data).draw()
}
}
I hope this helps.
EDIT, concerning your comment below:
You can use a normal jQuery ajax call. Something like this:
function loadDeviceInputsTableData(deviceID){
device_id = deviceID;
$.ajax({
type: 'GET',
url: `SomeURLhereAppendingthedeviceIDParameter`,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
// Transform the AJAX's response here and get the data to add to your data table below
deviceInputsTable.clear().rows.add(data).draw()
}
});
};
To trigger the ajax again on change of the input, you can call the on change function in jQuery.
$('#id_input').on("change",function(){
loadDeviceInputsTableData($('#id_input').val());
});
This issue was solved by using datatable's API, my question was about changing the ajax url dynamically upon user input. Here's what I did:
// Get device ID from wherever user inputs it, in my case it was a button with id: id_input
device_id = document.getElementById('id_input').value;
// Dynamically set your datatable's ajax URL to whatever you want. I concatenated the device id
// string with my url string. ajax.url("your URL") is enough to set the URL
// .load() is for getting data from the new URL you've just set.
$('#device_inputs_table').DataTable().ajax.url(
"/api/device_input/?format=datatables&device_id=" + device_id).load();
Doing this gave me the final URL: "/api/device_input/?format=datatables&device_id=1" (if user inputted 1) fixing my issue.
I making a .Net web app using a third party gridview(DevExpress web form ASPxGridView).
Lets say I have two grids(Grid1 and Grid2, both devexpress).
I am running into an issue where I need to update values in Grid2 based on which column is clicked on Grid1(during the onClick event).
I am able to capture the row and column in JavaScript but am not able to pass it back to my serverside code.
The grid has some settings tied to the edit mode, that if the page does a full postback, the grid loses its edits.
I have tried setting a HiddenField and calling a postback, but that erases edits in my grid. I have tried passing the variables to a static method , but I cannot access the controls on my page to update Grid2. I have looked into trying to do a callback instead of a postback, but it looks like callbacks are referencing Client-Side methods.
Does any one know of a way to pass a client-side variable to c# without a postback, or to call a non-static c# method from JavaScript? Any suggestions would be greatly appreciated.
The most basic approach to do this would involve two parts, part 1) add an ajax js function on your your existing grid page to handle the click event and make the data request. Part 2) Code up a separate C# web page to receive your client-side Grid1-variable, process it accordingly, and then respond with the data for Grid2. Here's some pseudocode of what the ajax call might look like, hope it helps.
//in your javascript section
$("#Grid1Cell").click(function(){
$.ajax({
type: "GET",
url: '#Url.Action("GetGrid2Data", "SomeController")"?yourVar=' + encodeURI(yourVal),
//alternatively url: "yourNonMVCpage.aspx?yourVar=" + encodeURI(yourVal),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.SomeValues == "blah") {
$("#Grid2Cell").text(response.SomeValues); //update Grid2
}
}});
});
If you need to "connect c#", it is necessary to perform a request to the server (using any of the available techniques - callback, postback, etc.).
If you need to refresh another control (Grid2) rendering during this request, the corresponding HTML content should be returned as a results of this request.
According to the provided description, you need to implement "cascaded grids" - i.e., update a dependent grid when changing a main grid. If so, use the approach illustrated in the https://github.com/DevExpress-Examples/how-to-show-detail-information-in-a-separate-aspxgridview-e70 example and force the dependent grid custom callback (and further refreshing) via the client-side PerformCallback method + handle the server-side CustomCallback event.
I have an issue which I don't quite know how to approach.
I need to extend the Sitecore Insert link functionality: when I insert a link to a Sitecore Item, a certain icon, based on some logic (I've already created the logic for another user story(*)), needs to appear in the front of the link after "Insert" button is pressed, and of course, finally on the UI.
I was thinking on the following approach: after the item is inserted, the item's ID is sent to the backend via an Ajax call and the response is a mark-up with the values returned by the service I told you above at (*).
The issue is that I don't know where to start on or if my idea is ok.
Any help is welcome.
I found the answer:
In the RichText Commands.js file, I have added the following script which sends the item Sitecore ID to the API:
function scInsertSitecoreLink(sender, returnValue) {
if (!returnValue) {
return;
}
var url = returnValue.url;
var itemId = url.substring(url.indexOf("=") + 1, url.lastIndexOf("&"));
var $ = jQuery.noConflict();
$.ajax({
async: true,
type: "GET",
url: '/sitecore/api/Test/ThisIsTheTestApiCall',
data: JSON.stringify(itemId),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result);
}
});
[...]
}
First I have added var $ = jQuery.noConflict(); before the ajax call;
More info here: https://api.jquery.com/jquery.noconflict/
Then I've checked if there are any changes over the routes: RegisterHttpRoutes;
Profit.
You might be better to modify the renderField pipeline, because if you ever need to change these icons later, you're going to have to process every single link on your site.
To do that, you'll want to create a processor and have it run before Sitecore.Pipelines.RenderField.ExpandLinks, Sitecore.Kernel in the renderField pipeline so that you can use the dynamic links (which contain IDs) to figure out what icons you need. From there you can use HtmlAgilityPack.HtmlDocument to find and update the markup when the link is rendered.
I created responsive tabs just using css. But when I try to implement ajax calls, i am bit confused.
I have a few questions:
What is the best way to make ajax request for each tab?
Is there any shortest way to append response to "tab" div?
How can I call ajax on page load for selected tab?
After first click on tab, do not need to make ajax call again. I need to cache response, but "cache:true" does not work.
Also any other improvements, suggestions and corrections would be helpful.
Example: JSFiddle
if you must use ajax i would run a loop through all the data you need to load do it at once an store the data in a variable (or object in this case)
than the change event will get the id from the tabData which is already populated and you won't need to call the ajax pages again.
now this will solve your cache problem since you won't need it for this scenario
if you want to instant populate the first selected tab when you open the page created an if statement in the ajax success
end result would look something along these lines:
$(document).ready(function() {
//data for the tabs
var tabs = {
1:"tabone",
2:"tabtwo",
3:"tabthree"
}
//empty object for now will be filled with ajax data
var tabData = {};
var activeTabVal=1;
var activeTabID = $('input[name=tabs]:checked', ".tabs").attr('id');
for(key in tabs) {
ajaxCall(key);
}
$('.tabs input').on('change', function() {
var activeTab=$('input[type="radio"]:checked', '.tabs').val();
var tabElement = $('input[name=tabs]:checked', ".tabs").attr('id');
//since we have the data already no need to call ajax here we just get it out of our already loaded data
var data = tabData[activeTab];
replaceData(tabElement, data);
});
function ajaxCall(key){
$.ajax({
type: "POST",
dataType: 'jsonp',
url: 'https://jsonplaceholder.typicode.com/posts/'+key,
async: false,
cache: true,
contentType: "application/json; charset=utf-8",
success: function (msg) {
tabData[key] = msg.body;
//use this to imediatly populate the selected div fo your second point
if(key == activeTabVal) {
replaceData(tabs[key], tabData[key]);
}
}
});
}
function replaceData(tabElement, tabData) {
$('#'+tabElement).next().next().closest('div').append(tabData);
}
});
I would instead of calling it on change I would call it on tab button clicked
Give your tab a data-id and the corresponding container div the same data-id, then when you append you can do something like $('.tab-container[data-id='+$(this).attr('data-id')+']').append('The content');
If you bind it to click you can simply run $('.tab-button .active').trigger('click');
If I were you I would store the data into the data portion of the container div and retrieve it again when they click on it again. So you just check if it was set, if not then do ajax call, if it was just pluck it out and display it. https://api.jquery.com/jquery.data/
I need to fire asp.net (link button or Button) click event(server side code) using Jquery, the buttons are in an update panel. Kindly help.
Michael's solution is good.
But I think it is safer to call GetPostBackEventReference.
The internal structure of ASP.NET Page may be changed in the future.
Here's the sample Code.
<%= Page.ClientScript.GetPostBackEventReference(lnkButton, "") %>
How about:
__doPostBack("<%= lnkMyButton.UniqueID %>", "");
What you need to do is to define your server side code as [WebMethod] once you do that your classname will be available to client side code for calling.
Then you would go about calling that method using something like this:
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{}',
dataType: 'json',
url: 'MyPage.aspx/SomePageMethod',
success: function(result){
alert(result);
}
});
I am more of a C# person, but I would imagine if you read this page you are easily able to make it in VB: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Below is how I triggered a click event with a LinkButton within an Update Panel. I couldn't get the ID until run time due to the way I was creating buttons, that is, it kept appending a _0, _1, etc to the end of the button name. For example on the server I would create 2 buttons with ID's say of 111555 & 222666. It would rename the buttons with ID's like:
contentMain_gridviewMessages_111555_0
contentMain_gridviewMessages_222666_1
So the first thing I did was create a unique attribute I could search upon, in my case the message id:
var msgLink = ('a[messageId="' + messageId + '"]');
After that I used a little bit of jQuery to get the auto generated ID:
var id = $(msgLink).attr("ID");
When I got the ID good ole fashion javascript did the rest:
document.getElementById(id).click();
Hope this helps someone out.