I have a webform that contains a file upload button.
when I click on the button to upload the file, the C# code behind contains some code in the event handler that I want to execute first before jquery executes.
<script>
$(document.ready() {
$('.uploadButton').click(function() {
// do some additional processing *AFTER* code behind stuff executes
});
}
</script>
// In my ASP.NET C# code behind
protected void uploadButton_Click(object sender, EventArgs e)
{
// Code to fire off here *FIRST* before jquery executes
}
Is something like this possible? I know I can implement a jquery post in my javascript, but since I have most of the code already laid out (and am changing this on a client request), I was just wondering if something like this was possible.
It's not possible
The OnClick and jQuery event handlers are executed first and only after that the page is posted back and you're able to run the code in in your server.
The best thing that you can do is to use $.ajax
here's some code to help you.
In your code behind
[WebMethod]
public static string uploadButton_Click(string name)
{
return "Good bye World! by" + name ;
}
And in js file
$(".uploadButton").click(function(){
$.ajax({
type: "POST",
url: "PageName.aspx/uploadButton_Click",
data: "{'Name':'Mr.X'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d) // will show up an alert box with Good bye world by Mr.X
}
});
});
You don't need to use the jQuery click handler. Wrap your code in a function and assign that function name to the OnClientClick property of the button. You can return false to prevent the post-back from processing.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
Ajax is the best option to choose. If you dont wannna use AJAX, then probably u can do this(perhaps the dirty-logic)
Do nothing with jQuery before the server is hit. In your code-behind
// In my ASP.NET C# code behind
protected void uploadButton_Click(object sender, EventArgs e)
{
// Code to fire off here *FIRST* before jquery executes
string strClientQuery = #"<script type="javascript"> $(document.ready() {
$('.uploadButton').click(function() {
// do some additional processing *AFTER* code behind stuff executes
});
} </script>";
Response.Write(strClientQuery);
}
If you want to keep the script strictly in client-side(i.e aspx page), then create the query as string in the aspx and pass it as an input to the page(through _EventTarget and in code-behind get the string and do response.write If you find the answser is useful, please take a few seconds to rate it
Related
I have filled the data using Ajax Method [WebMethod] and Data is filling and next I have maintaining all logic from my server side code using SelectedIndexChanged event AutoPostBack="true" and I have used this dropdown control inside the UpdatePanel control in master page MasterPageFile="~/MasterPage.Master" CodeBehind="AutoTrade.aspx.cs"'.
ASP code :-
<asp:ScriptManager ID="scriptmanager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="updatepanel" runat="server">
<ContentTemplate>
<asp:DropDownList ID="AutoTradeTop_expdate" ClientIDMode="Static" AutoPostBack="true" OnSelectedIndexChanged="AutoTradeTop_expdate_SelectedIndexChanged" runat="server" CssClass="form-control">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
Ajax code :-
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
//url is the path of our web method (Page name/function name)
url: "AutoTrade.aspx/PopulateExpDate",
data: "{}",
dataType: "json",
//called on jquery ajax call success
success: function (result) {
$('#AutoTradeTop_expdate').empty();
//$('#AutoTradeTop_expdate').append("<option value='0'>--Select--</option>");
$.each(result.d, function (key, value) {
$("#AutoTradeTop_expdate").append($("<option></option>").val(value.ID).html(value.ExpDate));
});
},
//called on jquery ajax call failure
error: function ajaxError(result) {
alert(result.status + ' : ' + result.statusText);
}
});
.cs code :-
[WebMethod]
public static List<AutoTradeExpDateRes> PopulateExpDate()
{
List<AutoTradeExpDateRes> autoTradeExpDateRes = new List<AutoTradeExpDateRes>();
try
{
string expdateres = GetAPIResponse("ssss://xxx.com/fns.aspx?otype=analyse_expdate&uid=" + "62" + "&symbol=" + "nifty" + "&instrument=" + "ce" + "");
var expdatelst = JsonConvert.DeserializeObject<List<AutoTradeExpDateRes>>(expdateres);
if (!ReferenceEquals(expdatelst, null) && expdatelst.Count > 0)
{
for (int i = 0; i < expdatelst.Count; i++)
{
autoTradeExpDateRes.Add(new AutoTradeExpDateRes
{
ID= i,
ExpDate = Convert.ToString(expdatelst[i].ExpDate)
});;
}
}
return autoTradeExpDateRes;
}
catch (Exception)
{
throw;
}
}
When I run this above code I'm getting the output Example Image :-
But when I use codebehind SelectedIndexChanged event and select any one of the list vale from the dropdown list (the data is erasing)
protected void AutoTradeTop_expdate_SelectedIndexChanged(object sender, EventArgs e)
{
}
The dropdown list data is erasing example img
Note :- I know we can handle this data functionality by using this client side onchange event but my question can I handle this ajax filled data from server side ? (once event SelectedIndexChanged is triggering the data is erasing )
So I want to keep the data using this SelectedIndexChanged event without data erasing and my next functionality should work. Please suggest me how can I achieve this. And what are the possible ways.
(The main reason I'm asking this question is initially my dropdown data should load (I wrote ajax call for that) and next if I change any dropdown value my next functionality should work (dependency is there to another dropdown list) so if I write the onchange event for clientside I need to write the 'Ajax' call for that and should fetch data form 'WebMethod' codebehind (should write one for loop) and next that return list data should fetch and write another for loop in ajax call to avoid this repeat logic can we handle from codebehind like my above question.)
I have raised one query in comment session that is :
I'm filling the ddl from server side using UpdatePanel and OnSelectedIndexChanged event, the code is executing fine but the autocomplete textbox logic is not working why?
I found the solution for that query and it is working fine for me.
This is the main part of autopostback not working properly.
<script type="text/javascript">
//On Page Load.
SetAutoCompleteGuest();
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
SetAutoCompleteGuest(); // in this method write your code.
}
</script>
This is sort of a Catch-22 with my ASP.NET (Sharepoint) WebPart/page. I need to respond to a button click, but doing that requires that the code be client-side (jQuery), because server-side/code-behind seems only to be available for the "Submit" process, and I don't want to submit the page in this scenario.
To be more clear, this is what I can do to have a button (an HtmlButton, to be more precise), and respond to clicking it without submitting the form:
Server-side (C#):
HtmlButton btnAddFoapalRow = null;
. . .
btnAddFoapalRow = new HtmlButton();
btnAddFoapalRow.Attributes["type"] = "button";
btnAddFoapalRow.InnerHtml = "+";
btnAddFoapalRow.ID = "btnAddFoapalRow";
this.Controls.Add(btnAddFoapalRow);
Client-side (jQuery):
$(document).on("click", '[id$=btnAddFoapalRow]', function (e) {
... script elided for brevity
});
This works fine.
I can do it all on the server side (in C#) for the "submit" button, like so:
Button btnSave = new Button();
btnSave.Text = "Save";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);
. . .
private void btnSave_Click(object sender, EventArgs e)
{
. . . code elided for brevity
}
But the crux of the problem is that I need to respond to a button click without submitting the form, but then run some code on the server side. I can fulfill the first requirement in jQuery (as shown above with HtmlButton btnAddFoapalRow), but I need to ultimately call some C# code in response to the click - I need to carry out an action on the server side.
So my question is: How can I, from the client-side code, "poke" the server-side code to "wake up and call this (some) function"?
Maybe I can update a variable (HiddenField) that I create in C# like so:
HiddenField PDFGenBtnClicked = null;
. . .
PDFGenBtnClicked = new HiddenField();
PDFGenBtnClicked.ID = "pdfgenbtnclicked";
PDFGenBtnClicked.Value = "no";
this.Controls.Add(PDFGenBtnClicked);
...from the jQuery, like so:
$(document).on("click", '[id$=btnGeneratePDF]', function () {
$('[id$=pdfgenbtnclicked]').val("yes");
});
..and then have code like this on the server-side to kick off the calling of the method:
if (PDFGenBtnClicked.Value == "yes")
{
GeneratePDF(listOfListItems);
}
...but how can I cause this (last) bit of code to be called? Can I put a timer on the page, and have it check the status of PDFGenBtnClicked.Value every so often? This is probably possible, but almost certainly Goldberg-esque.
Who has a better idea?
UPDATE
Theoretically (I think!) this should work (non-Ajax way to indirectly run server-side code from client-side code):
0) Create the Timer
private Timer tmr = null;
1) Create the "Generate PDF" button and the Timer:
btnGeneratePDF = new HtmlButton();
btnGeneratePDF.Attributes["type"] = "button";
btnGeneratePDF.InnerHtml = "Generate PDF";
btnGeneratePDF.ID = "btnGeneratePDF ";
this.Controls.Add(btnGeneratePDF);
tmr = new Timer();
tmr.Interval = 3000; // three seconds
tmr.Tick += TickHandler;
tmr.Enabled = true;
2) Call the method when the Timer trips:
private void TickHandler(object sender, object e)
{
GeneratePDF(listOfListItems);
}
3) Run the code if the user selected the "Generate PDF" button:
private void GeneratePDF(List<ListColumns> listOfListItems)
{
if (PDFGenBtnClicked.Value != "yes")
{
return;
}
tmr.Enabled = false; // only run this once, after val has changed to "yes" by the user clicking the "btnGeneratePDF" button (set from "no" to "yes" in jQuery's response to the clicking of the button)
. . .
However, I have a breakpoint on the first line of GeneratePDF(), and I'm not reaching it, dod-durn it.
UPDATE 2
I even added another event handler, for init:
tmr.Tick += TickHandler;
tmr.Init += InitHandler;
tmr.Enabled = true;
message.Text = "Converting the data to a PDF file has been successful";
(I do see the message Text, although it's not true).
With breakpoints in both methods:
private void TickHandler(object sender, object e)
{
GeneratePDF(listOfListItems);
}
private void InitHandler(object sender, object e)
{
GeneratePDF(listOfListItems);
}
...neither is ever reached. Why not? Theoretically, this seems like it should work...(I know, everything works in theory).
What you're looking to accomplish can be done by webservices and ajax.
Jquery.ajax can be used to send a request to a webservice (or webpage, or whatever). Here is an example from one of my websites:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "FoamServices.asmx/GetFoamNames",
data: "{'term':'" + $("#txtFoamName").val() + "'}",
success: function (data) {
//whatever you want to do with the data
},
error: function (result) {
alert("Error");
}
});
More information on this example can be found at Jquery.ajax website, but the gist of it is that I have a webservice set up, FoamServices.asmx and the method GetFoamNames in that webservice. GetFoamNames takes "term" in for a parameter. Upon success, I take the data I've received from that website and do what I want (check a true value, inject it into the page, whatever).
On the server side, here's my webservice:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class FoamServices : System.Web.Services.WebService {
public FoamServices () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string[] GetFoamNames(string term) {
List<Foam> foams = Foam.Read(term);
string[] foamNames = new string[foams.Count];
for(int i = 0; i < foams.Count; i++)
{
foamNames[i] = foams[i].FoamName;
}
return foamNames;
}
}
This is the basic set up for a webservice that also allows it to accept parameters from a javascript (JQuery) request.
What my service is doing is querying a search term against a database and returning the results. This is the basic setup for an autocomplete JQuery box.
You can adapt this to whatever you like, or you can also use ajax to call a webpage instead of webservice and have it do something.
Hope this helps!
The short answer to your question is that you'll have to use ajax, jQuery has some information regarding using it - https://learn.jquery.com/ajax/.
The longer answer is you'll need to do something like this:
$(document).on("click", '[id$=btnGeneratePDF]', function () {
$.get('/some/route/', function(result) {
//do something with the response, or not depending on your needs
}
});
I'm not familiar with Sharepoint so I can't offer any help on that side, but the basics are that you'll need to create a new page that fires off your PDF generation and access it using ajax, then handle the results in whatever way is appropriate.
My only suggestion is that if you want to only refresh part of the page without doing a full postback, use either AJAX, a callback, or an update panel. Update panels are very simple, but depending on what your button actually does may not be the best option. Just in case though, here is an example
<asp:ScriptManager runat="server" ID="sm">
</asp:ScriptManager>
<asp:updatepanel runat="server">
<ContentTemplate>
<asp:button id="YourButton" runat="server" Text="clickme" onclick="function" />
</ContentTemplate>
</asp:updatepanel>
This will not cause a full postback, and IMO is simpler than AJAX, but like I said may not be the most appropiate solution depending on your exact situation
Here is a link you may find useful from the MSDN site if you want to read up on it.
I have an asp.net web application.
On clicking a button, on the server side some code is executed. If the code is successfully executed I want an alert popup box to be shown to the user informing them of the successful completion of the action.
Any ideas?
Kind Regards,
Fiona
Google "alert asp.net" will give you plenty of solutions using the javascript alert function.
Even better, googling "jquery alert asp.net" will give you jquery solutions (an html modal popup which is modal to the current page, but allows you to switch to other tabs in a tabbed browser).
server side code and clide side code run in different contexts,
I think your best approach would be to post with ajax or jquery like:
$.post(url,parameters, function(){
//this code runs after the post
alert('my message')
}
);
I suggest you a couple of solutions.
Create a Javascript onclick event handler that executes an AJAX call to your business code. The success callback of the call will display the alert. References here. I prefer this solution.
$.ajax({
type: 'POST',
url: 'path/to/my/business/handler.ashx',
data: ({/*my json data*/}),
error: function (request, status, error) {
alert("Something wrong here!");
return false;
},
success: function (returnData) {
alert("Everything fine here!");
}
});
Manage the onclick event with a server side event handler. When the business logic has been executed, you can register a javascript script that execute the alert. References here.
ClientScriptManager cs = Page.ClientScript;
Type csType = this.GetType();
cs.RegisterClientScriptBlock(csType, "handler", #"<script language='javascript' type='text/javascript'>alert('Eveything fine here!');</script>");
What is the best way to send values from JavaScript (client-side) to the server (asp.net) without refreshing the page?
I want to insert the data into a database but I don't want to refresh the page or change any data on it.
Simple way :
1- Import jquery into your page
2- create ur function in the cs file of the page like this
[WebMethod]
public static string Save(string param1,string param2)
{
string result;
//your code must return somthing string
return result;
}
3- in your aspx page create your function
function save(){
var param1 = 'value 1 you need to send to the server should be string';
var param2 = 'value 2 you need to send to the server should be string';
$.ajax({
type: "POST",
url: "pagename.aspx/Save",
data: "{param1: '"+ param1 +"' , param2 :'"+ param2 +"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function(result){
//Successfully gone to the server and returned with the string result of the server side function do what you want with the result
}
,error(er)
{
//Faild to go to the server alert(er.responseText)
}
});
}
4- Call this function on the button click
for more questions or descriptions of my code and script i'm here :)
An easy way is to use a page method or static methods on a page and use jquery to send or get data from the server side code. This link has a good walkthrough
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Ypu have to use Ajax techniques, JQuery, Asp.net, YUI, and the rest of api and libraries that let you use Ajax techniques.
The easiest one in Asp.net is using builtin Asp.net Ajax functionalities by adding a ScriptManager and UpdatePanel to your page
The technique is called Ajax and there are no shortage of tutorials and libraries (not to mention support in the big libraries such as YUI or jQuery).
No one actually answered this question. As, "Import jquery" "use ajax" etc. all negate the fact that the OP asked for a javascript solution. This is a one-liner in javascript / very easy to do.
In your javascript you just call the method:
PageMethods.SomeMethod('test');
Your "SomeMethod" would be a code behind method like this:
[WebMethod]
public static string SomeMethod(string param1)
{
string result = "The test worked!";
return result;
}
Rules:
You have to identify your code behind method with a WebMethod attribute. It has to be static. And you have to register a script manager in your page as follows:
<asp:ScriptManager ID="MyScriptManager" runat="server" EnablePageMethods="true" />
Since I am working with an aspx webforms page to do some really simple javascript functions like retrieving / stashing geo location, I put it inside the Form element as required.
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>