I have the following JS code.
var thisItem = document.thisItem;
var e-mail = thisItem.getProperty("email");// which gets the e-mail of the User
And I have the following C# code.
public static void Main()
{
string username = "username";
string email = "";
//code to send a mail to the user
}
In JS code I' m using applyMethod("CSProgramName"); to run the C# from client side.
Here I want to use the Javascript 'e-mail' variable in C# code. How Can I do this?
This is not possible.
Have some hidden text box and assign the value through javascript and access the control.
If it is ASP.Net I would suggest to use ajax post to your C# code like below.
var reqUrl = "http://mysite/Sample/Sample.aspx?post=true";
var jqXHRresponse;
var request = $.ajax({
url: reqUrl,
type: "POST",
data: {email:emailAddress},
dataType: 'json'
});
protected override void OnInit(EventArgs e)
{
if (Request.Params["post"] == "true")
{
string email = Request.Params["email"];
}
}
Related
i am using jquery ajax function ,i recieve the data in success function if place Response.End() at server side i didnot understand what is the reason behind this????
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "WebForm1.aspx",
type: "POST",
datatype: "json",
success: function(data) {
alert(reuslt.CustomerID);
}
});
});
In WebForm1.aspx
protected void Page_Load(object sender, EventArgs e)
{
Customer c = new Customer();
c.CustomerID = "1";
c.ContactName = "Jhon";
c.CompanyName = "Dell";
JavaScriptSerializer serializer = new JavaScriptSerializer();
String response = serializer.Serialize(c);
Response.Write(response);
Response.End();
}
Customer Class
public class Customer
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
}
You are not using a Webmethod, which means de .aspx file still gives response of the HTML. The Response.end() ends the response, which means no further code is executed.
What you need to do is:
In the VB file:
[System.Web.Services.WebMethod(BufferResponse=false)]
public Customer getCustomer()
{
//implementation code
return new Customer(); // The code you need
}
jQuery:
$.ajax({
type: "POST",
url: "WebForm1.aspx/getCustomer", // Webmethod function here
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async:false,
success: function (json) {
var msg = JSON.parse(json.d);
alert(msg.customerID);
},
failure: function () {
alert("Sorry,there is a error!");
}
});
Information:
Webmethod
jQuery ICM webmethod call (stackoverflow answer)
More info can be found by search jQuery c# Webmethod on Google.
UDPATE
Because Ali want's to specific know why with response.end and without that it fails. Because with response.end will end the request. So no furter code is executed. Which means the HTML is not rendered. Without this code the HTML is rendered and also reponded as the response. Which means the JSON + HTML are the output of the request.
Sends all currently buffered output to the client, stops execution of
the page, and raises the EndRequest event.
Since Response.end throws an exception as quoted from the documentation (above). It is better to use HttpContext.Current.ApplicationInstance.CompleteRequest
I don't know the exact output off hand, but the idea is that you web forms (.aspx) use a page lifecycle. If you don't end the lifecycle by calling Response.End(), the page will continue processing and emitting to the output stream.
Thus, it will eventually reach its render stage and write out the contents of the .asxp file if you don't tell ASP.NET to stop outputting to the response stream.
Try using Fiddler to view the resulting response/html if you don't call Response.End() to see what is returned.
(And also what #Niels said-- my answer is more for a non-ajax implementation)
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 was looking on internet for over 2 hrs now, trying to find simple example of how to fill jQuery Variable from serverside code on load of asp.net page.
What i have so far:
I have a button which call this jquery code:
function GetListOfQuestions() {
$.ajax({
type: "POST",
url: 'UserProfile.aspx/getQuestions',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: OnAjaxError,
success: AjaxSucceeded
});
//$.getJSON('UserProfile.aspx/getQuestions', {}, function (data) {
// alert(data);
//});
}
function AjaxSucceeded(result) {
alert(result);
}
GetListOfQuestions calls serverside :
[WebMethod]
public static List<Question> getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return list.ToList();
}
result return an object if I alert it, so it must contain some kind of data, but I can't find any example of how I can retrieve data again on client side.
I'm not sure if what I am doing right now is right at all (I'm new to jQuery). So how can I retrieve data from result variable again?
There could be better ways but this is one way I know of:
[WebMethod]
public static string getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return new JavaScriptSerializer().Serialize(list.ToList())
}
In your jQuery method, you can
result = $.parseJSON(data) ;
Do a console.log(result) to see how to iterate through result, should be just a for loop.
Put a hidden field on your page an set the variable value there, later read the hidden value from js.
Another option is to use ScriptManager.RegisterStart UpScript to write your variable directly as js to the page.
I am using the web kit browsers local database to temporarily store some data and when I want to access it I create an object
function patientSelectHandler(transaction, results) {
var row = results.rows.item(0);
var patient = new Object();
patient.name = row['name']
patient.dob = row['dob']
patient.gender = row['gender']
}
Is there a way to access this object from code behind, without having to populate textfields/labels/dropdowns and then get the values from there?
example as it is now:
function patientSelectHandler(transaction, results) {
var row = results.rows.item(0);
var patient = new Object();
patient.name = row['name']
patient.dob = row['dob']
patient.gender = row['gender']
$('#txtPatientName').val(patient.name);
$('#txtDOB').val(patient.dob);
$('#ddlGender').val(patient.gender);
}
edit:
Updating my example a bit:
var patientString = JSON.stringify(patient);
var inputField = $("<input type='text' name='hiddenField" + i + "' id='hiddenField" + i + "'></input>");
$('#Patients').append(inputField);
$('#hiddenField' + i).val(patientString);
and then a loop in the code behind
for (int i = 0; i <= count; i++)
{
string n = String.Format("{0}", Request.Form["hiddenField" + i]).ToString();
JObject o = JObject.Parse(n);
string name = (string)o["name"];
//now I can get all values into variables and use them when calling the web service
}
You don't need to set it to textfields for any reason...
I would probably do something like
var patientString = JSON.stringify(patient);
$('#myHiddenInput').val(patientString);
Otherwise, depending on the flow of your application, you can post that object in string form to the server using AJAX.
Then, you will have to use a method to parse that string back into object formation. I'm not to familiar with c# but i'm sure it would be easy to find or write such a method.
If you have many fields to send, you can JSON encode everything and put it into a single multiline text field (textarea). Then you can easily decode it on the server.
Keep in mind -
When your server code runs, it builds up a page object that it then uses to generate html to send to the browser. Once the html is generated that page object is destroyed. By the time the browser shows your page, your server resources don't exist any more.
When the browser submits a request for a page, it destroys the DOM for whatever page it's showing. So by the time your server starts, your javascript doesn't exist any more.
Thus, the two systems are normally completely separate. You can get around this by passing ajax json messages between client and server.
I would use AJAX post to store your JSON object on the server.
var str = JSON.stringify(...);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/validate",
data: str,
error: function(XMLHttpRequest, textStatus, errorThrown) {
...
},
success: ajaxCallback,
dataType: "json"
});
And on the server
[WebMethod]
public static string validate(Dictionary<string, object> patient)
{
...
//return your JSON response
}
And then just iterate through Dictionary object on the server (key - object parameter, value - it's value).
Here is my JS:
function declassifyAjax(e) {
var items = getSelected();
var docIds = new Array();
items.each(get);
//get ids of QcItem/docId we are dealing with
function get(count, el) {
docIds[count] = $(el).parent().attr('id');
}
var dataObj = new Object();
dataObj.batchId = batchId;
dataObj.docIds = docIds;
var dataString = JSON.stringify(dataObj)
//make call to webservice to get html to recreate view showing
//pending declassification
$.ajax({
type: "POST",
url: applicationRoot + 'Models/BatchQC.asmx/declassify',
data: dataString,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (ProcessWebMethodResult.processWebMethodResult(data) == true) {
declassifyProcess(data, e);
}
},
error: function (e) {
alert("Failed to Get declassification details");
}
});
}
And here is my Web Service:
//type to represent the input the declassify method
public class DeclassifyType
{
public int batchId;
public string[] docIds;
}
[WebMethod(EnableSession = true)]
public WebMethodResult declassify(DeclassifyType dataString)
{
}
Any and all help appreciated!
Debugging in Firebug shows that the variables dataObj, batchId, docIds and dataString are correct. There is something wrong with the way my Web Method signature is setup I think, because the Ajax is never fired off. When stepping through the .ajax method, it goes to error, not success.
Your web methods expects one parameter, the data object you already have, but you're passing multiple parameters since you're passing the object directly.
Instead, you need to have an object with one property, dataString, and that property's value should be your object, like this:
var dataString = JSON.stringify({ dataString: dataObj });
▲--should match--▼
public WebMethodResult declassify(DeclassifyType dataString)
Ah, I just fixed it,
just changed the signature to
[WebMethod(EnableSession = true)]
public WebMethodResult declassify(int batchId, string[] docIds)
{
}
Simple really. Thanks for checking my post!