I am trying to do the following :
function redirectContactOnClick(contactId) {
var enc=<%= QueryStringModule.Encrypt("cont="+ contactId)%>;
alert(enc);
//window.location = "Contacts/AddEditContact.aspx";
}
QueryStringModule.Encrypt is a function inside a c# class, the page raise an error saying :The name 'contactId' does not exist in the current context
You won't be able to pass your javascript variable (contactId) to C# method. Suggest to look a different solution for that, for example, making Generic Web Handler (.ashx) and pass there your contactId via ajax and get back whatever you expect from your Encrypt call.
You can call Server side(C#) function from javascript.
First you have include your script inside a ScriptManager runnable at server.
Then the javascript function can call the c# function (which is having an attribute of ([System.Web.Services.WebMethod] and must be static) can be accessed.
eg.
PageMethods.QueryStringModule.Encrypt("cont="+ contactId);
on client-side, and
[System.Web.Services.WebMethod]
public static void Encrypt(string id)
{
// Do something
};
on server-side
(Source: http://www.codeproject.com/Questions/727256/how-to-call-server-side-function-from-javascript)
For to call the Server Side member the only mode is do a request HTTP or sync (POST Page) o async (AJAX)
you don't call a server function directly
in the you case
receive an error because contactId not is an page's member you can comunicate with these way
ASP.NET Client to Server communication
Related
I try to pass my JS variable into razor, my script fragment:
select: function (event, ui) {
var docID = ui.item.DoctorCode;
#{
string org_code = _unitOfWork.Doctors.GetById("").OrganizationCode;
}
doctorOrgLabel.text('#org_code');
}
In GetById() method i want to pass JS variable docID. I'd appreciate any help!
I try to pass my JS variable into razor
This sentence makes strictly no sense at all.
Razor is a view engine used by the ASP.NET MVC framework running on the server to produce some HTML template.
javascript on the other hand is a client side language running on the client. Once the HTML template is rendered to the client and javascript starts to execute there's no longer such notion as Razor.
If you want to pass some javascript variable to the server you have a couple of options:
make an AJAX call to the server
set the value of this variable in some hidden field inside a form and submit this form
use window.location.href to redirect to the server and passing the variable as query string parameter
store the javascript variable in a cookie which will be sent to the server on subsequent requests
I have a Ajax form in my asp.net mvc application, which has a onSuccess callback as below:
function onSuccessReport(context)
{
$('reportChart').empty();
var line1=#Html.GetStrippedString(context.Expenses);
}
I defined a html helper which accept an string an manipulte it and return a string.
What I pass to onSuccessReport, is a json result which has a structure like this:
But I cant send context.Expenses and the application throws syntax error.
How can I send a javascript variable to my helper?
Thanks
Edited:
The error in my view
****Error 1 The name 'context' does not exist in the current context****
C# method
json = json.Replace("\"Date\":", string.Empty);
json = json.Replace("\"Total\":", string.Empty);
json = json.Replace('}', ']');
json = json.Replace('{', '[');
return MvcHtmlString.Create(json);
You are mixing client side code (javascript) with server side code (HtmlHelper). You cannot pass client side variables to server side helpers. If the context variable is known only on the client then you will have to write a client side javascript function instead of server side helper. So move to logic you wrote in this Html.GetStrippedString helper into a javascript function that you could call from your script.
Actually, you can send javascript values over to the server side if you use Ajax. Instead of using your helper method the way you are, just change it into an action within the Controller to return you some Json (could just be a string, number, object, etc, etc). Here is an example of what you might try out.
View
function onSuccessReport(context)
{
$('reportChart').empty();
var expenses = context.Expenses;
$.getJSON('#Url.Action("GetStrippedString", "ControllerName")', { expenses: expenses }, function (data) {
//pending what you pass back as data, do whatever with it
alert(data);
});
}
Controller
public JsonResult GetStrippedString(string expenses)
{
var result = string.Empty;
//Do something to string
return Json(result, JsonRequestBehavior.AllowGet);
}
I have written a java script function in the skin file of the visual web Gui application which returns some value too. Now i am invoking the java script method from code behind.
public void XYZ( string message)
{
this.InvokeMethodWithId("testCall", message);
}
And javascript function is:--
function testCall(strGuid, txt) {
alert("hai Java script fired..");
return txt+ 'returned from JavaScript';
}
I want the value returned from JavaScript in the application. how can i achieve it. Is there in other method to invoke the methods of JavaScript?
I want something like this:--
public void Conect( string message)
{
string returnedvalue = this.InvokeMethodWithId("testCall", message);
}
Javascript is executed on the client so the return won't make it to the server.
A solution could be to use AJAX to send that value to the server. Stack Overflow is full of answers about AJAX.
Here's a good example.
#Amish Kumar,
As noted by other replies already, the client-side and server-side are not directly connected in web programming. The client is always the initiator of every request, and the server-side's "purpose" is to render a response, which will then be returned to the client for processing, in Visual WebGui this is usually some UI update processing. This basically means that your client script will not execute until the server-side has finished rendering the response, and the only way the client can get some message back to the server is to issue another request.
Think about how you need to use the MessageBox in Visual WebGui for instance. In order to receive the "response" from the MessageBox, you need to supply a callback handler in your server-side code, and then your server-side code will have completed creating the response, which is returned to the client. The client updates its UI and on some action to the MessageBox dialog, it sends a new request to the server, which interpretes the action and invokes your callback handler. In the callback handler you use Form.DialogResult to get the user action.
A very basic way to make this work in custom Visual WebGui code could be like the following code on a Form:
private void button1_Click(object sender, EventArgs e)
{
SendClientMessage("This is a test");
}
public void SendClientMessage(string strMessage)
{
System.Text.StringBuilder sb = new StringBuilder();
sb.AppendLine("var objEvent = mobjApp.Events_CreateEvent('{0}', 'MessageEvent');");
sb.AppendLine("mobjApp.Events_SetEventAttribute(objEvent, 'Msg', '{1}');");
sb.AppendLine("mobjApp.Events_RaiseEvents();");
this.InvokeScript(string.Format(sb.ToString(), this.ID, strMessage));
}
protected override void FireEvent(Gizmox.WebGUI.Common.Interfaces.IEvent objEvent)
{
if (objEvent.Type == "MessageEvent")
MessageBox.Show(objEvent["Msg"]);
else
base.FireEvent(objEvent);
}
This code will not work unless you set your Visual WebGui applicaton for no Obscuring. In order for this code to work on an obscured application, you would need to add the JavaScript as an obscured JavaScript resource and it would work fine.
Palli
enter code here
I have a project that uses PageMethods to call functions on the server.
The server functions (written in C#) return the values as array of strings, without doing any kind of serialization and in the client side (from Js) the accessing of the return values is by using static variable called arguments.
I found that sometimes for some users (cases are not repro) sometimes an exception occured
"WebServiceFailedException the server method 'Foo' returned invalid data.
the 'd' property is missing from JSON."
Some searching on google I found that people are serializing the return values using DataContractJsonSerializer class and in js accessing the return value using one of the callback function
Example:
function OnRequestComplete(result,
userContext, methodName) {
var Person = eval('(' + result + ')');
alert(Person.Forename);
alert(Person.Surname); }
So is the first technique is correct? or what?
P.S:
the function on the server is defined on the default.aspx.cs file as follows:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] Foo(string s);
from the client side the calling is as follows
PageMethods.Foo("value",OnSuccess);
Also all the users have the same browser version (IE8)
I don't know if it's the entire problem, but your first issue is manually serializing the return value. PageMethods and ScriptServices automatically JSON serialize their return values. Nesting two levels of JSON could definitely be throwing a wrench in the framework's client-side deserialization process (which is also happening automatically, before your eval() code).
To return an instance of your Person class, this is all you need:
public static Person GetPerson() {
Person p = new Person();
// Populate the Person object here.
return p;
}
Then, on the client-side you can work with the object's properties as expected:
function OnRequestComplete(result, userContext, methodName) {
console.log('Person name: ' + result.Forename + ' ' + result.Surname);
}
Alternatively, if you're using jQuery for other tasks and already have it on the page, you don't even need the ScriptManager and MS AJAX to call page methods. You can directly call page methods with jQuery and skip all that overhead.
Without knowing how the request is made and how the server end is coded, my answer may not be accurate.
Where is the WebMethod decorated method in your server side code? If it is an a separate class with the ScriptService attribute, and if JSON is specified while making the request, then the JSON values should have been automatically serialized and dont need to be serialized manually again. With this set up ASP.NET 3.5 wraps the response in a "d" object
Some users getting the exception might be due to the browser that they are using. If you are using jQuery, I'd specify the content type as so in the ajax request body
contentType: "application/json; charset=utf-8",
Hakeem
This is a bit funky. ASP.NET always adds the "d" to all results. So it either should work or not. Here is some background on the "d" issue:
http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/
How can I access an JavaScript variable from within an JSP page ?
My guess is that you're probably running Javascript on the client (in the browser), and Java in your JSP pages on the server. You can't access a client-side variable on the server. You can send a client-side variable's value from the client to the server for server-side processing. You'd probably do that via an Ajax call, or just by submitting a form.
Edit For example, this Javascript code sends the value of the foo variable to the server side page 'test.jsp' using the field name "foofield" (slightly different name to be clear). This uses Prototype, but jQuery, Closure, and all the other libs can do much the same thing, just with slightly different syntax:
Server-side Java (in the JSP) — this is just like getting fields from a form that's been submitted:
String foo;
foo = request.getParameter("foofield");
Client-side Javascript (using Prototype's Ajax.Request):
// Our client-side `foo` variable
var foo = "Hi there";
// Send it to the server via Ajax (Prototype version)
new Ajax.Request('test.jsp', {
parameters: {foofield: foo},
onSuccess: handleSuccess, // Function to call on success; not shown
onFailure: handleFailure // Function to call on failure; not shown
});
If you prefer jQuery for the client-side, here's that Prototype code rewritten for jQuery's ajax function:
// Our client-side `foo` variable
var foo = "Hi there";
// Send it to the server via Ajax (jQuery version)
$.ajax({
url: 'test.jsp',
data: {foofield: foo},
success: handleSuccess, // Function to call on success; not shown
error: handleFailure // Function to call on failure; not shown
});
You can't access it directly. That's because this is how a page is rendered:
1. On the server, the JSP code runs and generates HTML/JavaScript.
2. The HTML/JavaScript is sent to the client's browser.
3. The browser then renders the HTML and runs the JavaScript.
As you can see, the JavaScript is run way after the JSP runs, so they can't directly access each other's variables.
What you could do is output JavaScript code which initializes a variable based on a value in the JSP code. For example, if you generate code like this (excuse my syntax, I don't know JSP):
<script>
var JSPValue = /*jsp code that prints the value of a variable*/;
//rest of JavaScript code...
</script>
Then the JavaScript can accss JSPValue, just because it will have been put there by the server. For example, when sent to the browser, it might look like:
<script>
var JSPValue = 42;
//rest of JavaScript code...
</script>
Not possible. You can access a JSP variable in javascript but the javascript variable can not be accessed in JSP.
As the javascript is running on the client side and the JSp is running at the server side,it is not possible to access the javascript variable in jsp code,but u can acess that javascript variable in the server side by passing that variable along with the request as request parameters,As the request parameters are there in the request object which is available to jsp code ,u can access them.