Pass a parameter to server method using JavaScript - c#

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

Related

Push Table to screen

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');

Getting error when doing a jquery ajax function to a aspx page

I want to send data using ajax from jQuery to c# (note: I'm sending request to the same page).
I am following this tutorial http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/.
NOTE: This is a asp.net 3.5 on SharePoint 2010 webpart solution.
This is my jquery code:
$.ajax({
type: "POST",
url: getURLWithoutQuery() + "/saveOrder",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
// return the url of the current page without any query parameters
function getURLWithoutQuery() {
return location.protocol + '//' + location.host + location.pathname;
}
and in c#, the main file is PDFLibraryUserControl.ascx.cs. This is the one that has the Page_Load function.
However I have another class file called SaveStructure.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.Services;
namespace PDFLibrary.PDFLibrary
{
public partial class SaveStructure : Page
{
[WebMethod]
public static int saveOrder()
{
return 1234;
}
}
}
I expect to get an alert saying 1234, but instead I get this:
Does it have something to do with the function saveOrder being on another file than the main one? Or maybe my URL is not correct? I don't want to hardcode the URL in it, because the current page is the aspx page and also contains the jQuery code to send the POST (to the same page).
Does anyone know what's wrong and can fix this?
Putting page methods inside of a user control is a bad idea, because the biggest problem is that user controls are not directly accessible via script (read: jQuery) like .aspx pages are. If you are constrained to only putting this logic in a user control, then my recommendation is create a web service (.asmx) that will perform the logic the page method was going to do. A web service is directly accessible via the jQuery .ajax() method, like this:
Code from myService.asmx:
[WebMethod]
public static int saveOrder()
{
return 1234;
}
Code in SharePoint .aspx page:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "myService.asmx/saveOrder",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: handleSuccess,
error: handleError
});
});
function handleSuccess(data, status) {
// Do something with successful data retrieval
}
function handleError(xmlRequest) {
// Do something with error
}
</script>

How to return value to AJAX from code behind? [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
How To Return Value From Code Behind To AJAX?
This is my AJAX code
$.ajax({
type: 'POST',
url: 'country_management.aspx/save',
cache: false,
data: "{'parameter':'paramValue'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
if (data.d == "error") {
$('.success_box').hide();
$('.error_box').show();
}
else {
$('#name').val('');
$('.error_box').hide();
$('.success_box').show();
}
}
});
Code Behind:
[WebMethod]
[ScriptMethod]
public static string save(string parameter)
{
string name = HttpContext.Current.Request.QueryString["name"].Trim();
return "error";
}
after writing the first line, return statement does not return anything to the AJAX.
Without knowing the context of the whole application is kind of difficult to answer your question. (Does name get supplied from elsewhere in the app, you could make use of a session?)
But what is stopping you from passing the name through in the ajax call? Rather than just sending through'parameter':'paramValue'.
You have to remember your query string is supposed to contain the parameter you're looking for. at the moment it's looking something like.
http://www.somesite.com/country_management.aspx/save?parameter=paramValue
when you actually need
e.g.
http://www.somesite.com/country_management.aspx/save?parameter=paramValue&name=newName
Javascript
$.ajax({
type: 'POST',
url: 'country_management.aspx/save',
data: { parameter:'paramValue', name: 'newName'},
success: function (data) {
//do something with the response
}
});
Codebehind
[WebMethod]
[ScriptMethod]
public static string save(string parameter, string name)
{
PerformSave(name, parameter);
return "Data Saved!";
}
TIP
Try out this app. Fiddler. It's extremely useful when you're working with things like ajax calls etc. Actually any web development. :)
Because you didn't post any field or property "name"
If you do the ajax after clicked in a button inside form, data will be the form serialized.
Another thing is, why should you expect "name" var in query string, I don't see any url with aspx?name="any name"

Executing a C# method by calling it from client-side by ajax

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));
}

Calling a code behind method based on a click event

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.

Categories