I currently have this working but it requires me to have a static method as the method called in the code behind. I would like to be able to access some member variables that can't be static. I'm not married to the Javascript implementation and am open to other suggestions that would help me achieve this.
If there is other information that would be helpful let me know and I can include.
EDIT: Let me clarify, I'm looking to edit a value in one of the user controls on the page based on the button click. I am holding the user controls in a list on the page and using the parameters passed through the javascript to find the user control that I want to update and modify the value there.
It currently looks like this:
Javascript:
function incrementCompletes(obj)
{
var firstParameter = $(obj).parents('.parentClass1').find('.childClass1').html();
var secondParameter = $(obj).parents('.parentClass2').find('.childClass2').html();
var parameters = "{'firstParam':'" + firstParameter+ "','secondParam':'" + secondParameter+ "'}";
$.ajax({
type: "POST",
url: "Page.aspx/StaticMethod",
contentType: "application/json; charset=utf-8",
data: parameters,
dataType: "json",
success:
function DoOtherStuffHere(result) {
var x = $(obj).parents('.classWithStuffToChange');
var y = $(x).find('.otherClassWithStuffToChange');
y[0].innerHTML=" + " + result.d;
}
});
}
Code behind:
[WebMethod]
public static int StaticMethod(string parameter1, string parameter2)
{
//Do some stuff
//Return a value
}
I would like to find a solution that does not require the method called to be static.
If you want to access member varaibles of the page, there has to be an instance of the page class. That means that you have to do a postback instead of calling a web method.
Use a regular Button control, that will cause a postback and you can use it's Click event to run a method in the code behind. If you don't want the page to be reloaded, you can use ASP.NET AJAX to do the callback using AJAX.
Related
I have an AJAX request when a branch of my JSSTree is clicked
$("#jstree").bind("select_node.jstree", function(evt, data)
{
var idArgument = data.node.text;
$.ajax(
{
type: "POST",
url: "WebForm1.aspx/brancheSelectionnee",
data: JSON.stringify({ id: idArgument }),
contentType: "application/json; charset=utf-8",
success: function(msg)
{
;
}
});
});
So, I call this function, which make a new "page" (because it's static) and call a function that return a System.Web.UI.WebControls.Table.
public static string brancheSelectionnee(string id)
{
var page = (WebForm1)HttpContext.Current.CurrentHandler;
System.Web.UI.WebControls.Table tableau = page.brancheSelectionneeNonStatique(id);
var stringWriter = new StringWriter();
using (var htmlWriter = new HtmlTextWriter(stringWriter))
{
tableau.RenderControl(htmlWriter);
}
string tableauString=stringWriter.ToString();
return "randomstring";
}
Big problem here: My "tableau" is updated, with what I want (I see this with the htmlWriter) but.. I don't know how put it in my screen!
I have it in my C# code, but I want it in the screen, and not just here.
I have "tableauArticle" which is a real System.Web.UI.WebControls.Table, in my ASP.net code.
I tried some things, like putting "tableauArticle" as Static, then
tableauArticles = tableau;
But I didn't see any changement. I think that I updated a table in the page that I don't display
I think that the main problem is that my pagee isn't refresh or I do my tables wrong.
You do an AJAX request, so there is no page refresh. You just get a string (with HTML) back from your server method. You then have to manually put that string on your page. This happens in the success callback function which in your code is empty. As first step try something like this:
success: function(msg)
{
$('<div class="newtable">').html(msg).appendTo('body');
}
On the server-side your method brancheSelectionnee needs the AjaxMethod attribute so that it can be called with AJAX:
[Ajax.AjaxMethod()]
public static string brancheSelectionnee(string id)
(It also should return tableauString; not "randomstring", right?. And I am not sure if you can use the HttpContext.Current.CurrentHandler there, but that is for a second step if the basic AJAX stuff works.)
Here is one tutorial for all this which gives you an overview.
For the answer, it is 100% Raidri solution :
$('#tableauArticles').empty();
$('<div class="newtable">').html(msg.d).appendTo('#tableauArticles');
How To Fire An Event /Function From A Code Behind When I Type 6Th Digit In A Textbox ?
My uestion is very simple
I am a programmer of C#
how to fire an event /function from a code behind when i type 6th digit in a textbox ??
After reading your requirements from the comments in the question, I suggest you to use Web Service or Page method for your current problem.
Your problem can be solved in the following way:
Use jQuery in your project.
Write a javascript "onchange" function for your textbox.
Calculate length of the text in textbox in this javascript function.
When the length equals "6" then fire a web service request via jQuery.
The web-service shall return data that you need to capture in your javascript.
Display the data.
A sample code is as below:
Javascript function for calculating length:
function caculateTextboxLenth() {
if (document.getElementById("<Textbox Id>").length == 6) {
var text = document.getElementById("<Textbox Id>").text;
CallWebService("/getDistrictData",text);
}
return false;
}
Javascript function for calling web page method:
function CallWebService(WebServiceURL,text) {
$.ajax({
type: "POST",
cache: false,
url: WebServiceURL + "&pincode=" text + "&dt=" + new Date().getTime(), //This will append ?dt={timestamp} to the URL to prevent caching,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: ShowData,
error: error
});
}
Your C# page method shall be like the following in your code behind file.
[System.Web.Services.WebMethod]
public static string getDistrict()
{
int pincode = Convert.ToInt32(HttpContext.Current.Request.QueryString["pincode"].ToString().Trim());
string district = "";
//code to fetch district
return district;
}
P.S: Do check for SQL injections.
attach two events to textbox
1)Javascript onchange
2)c# OnTextChanged
check validations for characters in onchange and if true then "return true;"
which will fire OnTextChanged event on server side.
Also do no forget to put "AutoPostBack" property of textbox to true.
My solution may not be perfect but put your texbox in UpdatePanel double click it to create an event, now use int.Parse to see that if entered input is integer or not and use txtbx.Text.Length to see if you got the sixth digit or not.
it should be something like this
if(txtbx.Text.Trim().Length > 0 && int.Parse(txtbx.Text.Trim(), out intoutput))
{
if(txtbx.Text.Trim().Length = 6 )
{
// your code here
}
}
In my website, i'm declaring an array in javascript and insert them elements dynamically. So now, I want use that array from my C# code. I don't want use ajax to send that element to an web service... I just want use an C# event, like OnClick and access the array that was build in javascript.
I searched for an answer but I just found the oposite.
Thanks
The easiest way is AJAX call and i don't understand why you are avoiding that ?
Make an AJAX call from your button click.
look here a demo :
Ajax call is not calling to the server side and in httpfox shows error as "Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED)" in ajax post call
for example : covert your array to a json string and call a web client in your c# code. Here i have a button . on button click i want to send my GRIDVIEW data to c# method(web method).
you need to remember that while sending json data using stringfy() method,
in server side we need to define the parameter as object.
not any other format like string/int/bla bla.....
use Scripts/jquery-1.8.3.min.js
http://code.jquery.com/ui/1.10.3/jquery-ui.js
$('#btnResult').on('click', function () {
var mydata = [];
$("#<%=GridProjectDetails.ClientID %> tr").each(function () {
var myObject = new Object();
var id = $(this).find("input[name*='ID']").val();
var locationcode = $(this).find("input[name*='TextLocationCode']").val();
var Location = $(this).find("input[name*='TextLocation']").val();
myObject.id = id;
myObject.locationcode = locationcode;
myObject.Location = Location;
mydata.push(myObject);
});
var myString = JSON.stringify({ details: JSON.stringify(mydata) });
alert(myString);
var exportdata = myString;
$.ajax({
type: "POST",
url: "Default.aspx/ExportToExcel",
data: exportdata,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#Result").text(data.d);
},
error: function () { alert(arguments[2]); }
});
});
});
and server side method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ExportToExcel(object details)
{
return "Message : Success";
}
It's a kinda weird thing to do, but if you have to do it, you can do it by creating a form, inside the form have a hidden text field and call a function when submitting to update the value of this field.
The markup:
<form id="yourForm" method="post" >
<input type="text" name="hiddenFieldName" id="hiddenFieldName" hidden="hidden" />
</form>
The javascript:
void yourProcedure() {
var yourArray = ["Value1", "Value2", "Value3", "Value4"];
document.getElementById('hiddenFieldName').value = yourArray.join();
document.getElementById("yourForm").submit();
}
Then in the server, the form variable will contain "Value1,Value2,Value3,Value4".
I'm trying to execute a server side method using this technique:
Javascript Ajax function
function storeLocal(brand, type) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{brand:'" + brand + "'}",
url: "Jquery Site.Master/storeLocal",
datatype: "json",
success: OnSuccess(brand),
});
}
function OnSuccess(brand) {
alert(brand);
}
C# method:
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
}
line of code to execute is:
<li>
<a class="strong" onclick="storeLocal('petzl','harness')" href="About.aspx">Harnesses</a>
</li>
but its not executing correctly is there any particular error in my code?
reasone i am using this method is because i want to have a dynamic menu for a small project and wish to store in session what specific "li" did a user select in session so that i can load the content in the redirected page.
Thanks alot
Adrian
There is no return in your method that is might be the poblem, you method should be like as below
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
return "value" +brand;
}
There are a couple of errors I can see with your ajax request:
The url parameter value isn't a proper URL.
Your not assigning your OnSuccess method correctly.
Try changing it to:
function storeLocal(brand, type) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{brand:'" + brand + "'}",
url: "ProperSiteUrl/storeLocal",
datatype: "json",
success: OnSuccess,
});
}
And you aren't returning anything from your storeLocal web method. Try changing it to:
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
return ...;
}
Also, your sending JSON to the server, however, for a single parameter it you might find it easier just to send it as key/value pair e.g.
...
data: "brand=" + brand
...
i am not sure if your code is right! you have given both href and onclick and the page might navigate to about.aspx even before the onclick ajax event is completed.
try to remove the href or put the onclick event inside a href='javascript:storelocal()' and return the value from webmethod.
keep a breakpoint in the webmethod and see if the content is getting passed to the webmethod or not.
The url and success doens't look good.
1 - Within the ajax call you don't pass a argument to the success function. it will be returned something by the webmethod specified in c#.
you specify data in the data propriety, and that is used as the arguments passed to the webmethod.
2 - You can't call the webmethod using you master page, it has to be specified in the page that you are working. the aspx file not the master.
The page inherits from master, but it's not the master. Is a page with specification of the master page file.
Try this to identify errors, this for seeing what is returned
error: function (error) {
alert(JSON.stringify(error));
}
I have a public in my code behind page that takes a string.
I would like to call this method from javascript.
The parameter that I want to pass down is variable that changes from a ddl.
So I have something like this:
var value = document.getElementById('ddlContact').value;
<%=PopulateContactFields("value") %>
This passes down the word 'value' and not the data in value.
I can't figure out the proper syntax to pass down the data in value.
Thanks
As mentioned by others, trying to access C# code behind directly from javascript is impossible.
However, you can communicate with it indirectly.
I think your best shot is to use a combination of jQuery and the [WebMethod] attribute.
javascript function using jQuery to do an AJAX call:
function Search() {
var search = $('#<%= ddlContact.ClientId %>').val();
var options = {
type: "POST",
url: "Default.aspx/Hello",
data: "{'name' :'" + search + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
};
$.ajax(options);
}
Code behind:
public partial class _Default : System.Web.UI.Page
{
[WebMethod]
public void Hello(string name)
{
return "Hi " + name;
}
}
The code you are showing is executed server side when the HTML is generated. In other words it is executed BEFORE it hits the browser and your user had a chance to do anything with the page.
No matter what syntax you would use here the information you want cannot be accessed at this time - it does not exist yet.
The right approach here is to sent this information to the server either by posting the page or using AJAX and then, on the tail end of request/response cycle do your processing
Another option would be to do the processing client side using Javascript