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.
Related
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 am using the jquery.pageless plugin. It implements infinite scrolling by grabbing the params generated by a paginate method in the controller.
I am trying to pass custom parameters, such as a user ID, to my pageless function. This works when I load the function in js.erb, as follows:
$('#relationship_list').pageless({ totalPages: "<%= #reviews.count %>"/5+1
, url: '/reviews'
, params: {id: "<%= params[:id] %>"}
, loaderMsg: "loading"
});
This works as desired. However, I DON'T want to load my page remotely, and so I need to find a way to implement this in javascript, unobtrusively (I don't want to integrate a script directly in my view, I want to place the code in application.js).
That means I have to find a way to 'translate' code like <%=params=> to a variable that the pageless call can read from the controller. But how? I really have no idea how to do this.
I think this is a question best for people who know jquery.pageless already, and since it's so general there's no point in my adding my own code to this post - please comment if disagree!
This is the solution I picked. Any tips on whether this was the appropriate way to go is welcome:
if($('#relationship_list').length){
$.ajax({
type: 'GET',
url: '/users/'+$('.user_info').attr("id"),
dataType: 'json',
success: function(response){
$('#relationship_list').pageless({ url: '/reviews'
, totalPages: response["count"]/5+1
, loaderMsg: "loading"
, params: {id: response["id"]}
});
}
});
}
What this does is make an ajax call to the controller, and render a json param with the key parameters. I then use these parameters to implement the .pageless function.
Note that in order to get the original user ID I actually have a div that contains the user ID, and so I grab that from the page. The user ID is no state secret but if anyone has a tip on how to grab an html parameter (the ID is in params[:id] in my rails code) I would be super grateful
simply, i have an ASP.net Textbox inside a webcontrol
it gets filled by a javascript function inside the same markup of the webcontrol
the problem is that i need to read that value from the serverside events of the webcontrol
tried page_load, page_unload... but they all fire before the javascript function is executed.
i even tried to move the JS code to a seperate Script file, and added a reference to it.
but again its just the same.
when i try to call that function to fill the textbox, using:
Page.ClientScript.RegisterClientScriptBlock //which calls it to early
Page.ClientScript.RegisterStartupScript //which calls it too late ;P
but again it's executed before the Script reference is included in the render of the control.
any suggestions except of Registering all the JS code using registerClientScriptBlock?
im sure im missing something important related to the life cycle of the web control, so please enlighten me and sorry for the long blablabla.
thanks in advance
As Tim implied, this is probably better done on the server, prior to output.
However, to answer your question, you could create a webservice which the client could call to notify the backend of the calculated value. Here's a very rough example:
NewWebService.asmx:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void SaveTextBox(string textValue)
{
<%-- Save the value here --%>
}
YourPage.html:
// Requires jQuery.
// Code can be refactored to use any library or none at all, if you like
<script>
$("#textBoxId").change(function() {
var textValue = this.value;
$.ajax({
type: "POST",
url: "NewWebSerivce.asmx/SaveTextBox",
data: textValue,
contentType: "application/json; charset=utf-8",
success: function (data) {
// do nothing
}
});
});
</script>
Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")