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);
}
Related
I'm working on a jsp page and I need a Javascript variable as parameter inside a java function e.g.:
<script>
function example(string){
<% javaFunction(string); %>
}
</script>
how can I pass the javascript String variable to the java fucntion?
DONT USE SCRIPTLETS IN JSP!.
You must understand jsp (views) code is executed in client side, java one is at server (host) one.
In order to get variables from the host side, you have plenty vays, but for small things best option is to make an ajax call:
$.get( "javaFunction",
{ variable: "VALUE" }
).done(function( data ) {
alert("Java function returned " + msg);
});
In java you need to map the url:
#RequestMapping(value = "/javaFunction", method = RequestMethod.POST)
public
#ResponseBody
String javaMethod(#RequestParam("variable") String variable) {
if (variable.equals("VALUE") {
return "Correct call!";
} else {
return "Mistake!";
}
}
I have a controller with a function ShowEvents(EventCategory eventCategory). Is it possible to call this function from client-side JavaScript? I know that I can retrieve items from the database using the Sitecore.Services.Client (SCC), but is it possible to actually access methods? Maybe through the controller rendering, if that's possible?
Here is an example of a method I want to call:
public class EventListController : Controller
{
public ActionResult ShowEvents(EventCategory eventCategory)
{
var repository = new EventListRepository();
var eventPages = repository.GetEvents(eventCategory);
var eventListViewModel = repository.GetEventListViewModel(eventPages);
return View("/Some/Path/, eventListViewModel);
}
}
This is on Sitecore 7.5 MVC
You can Post to controllers from the client side using the format
/api/sitecore/{yourcontroller}/{action} in your case this would be /api/sitecore/eventlist/showevents passing the eventCategory as the data.
yes you can reach every function with
A separate view page named with same name of it and the view pages
will be written with RAZOR language which is composed of c# and html
and surely you can write javascript within the html code.
with the Asp.net and MVC5
here an example :::
http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started
You can use the below format for call the Action method in sitecore project.
Sitecore have own route to manage the action method which is used as API. You can use it for Ajax call from the fronted.
/api/Sitecore/{controller Name}/{action method name}
Just post your data as request in data object and cosume the url in above format. It's act like API.
I am making a website using Django and I want to pass a python object from my view (where it is created) through the Django template and to a Dajax call. The problem is that by the time it gets to dajax it has been turned into type unicode.
In my Template
<script>
var emailer = "{{emailer|safe}}"; <---If I omit the quotes here then I get a javascript error.
sessionStorage.setItem('emailer',emailer);
$(document).ready(function(){
$('.send').on('click', function(e){
var emailer = sessionStorage.getItem('emailer');
Dajaxice.InterfaceApp.sendEmail(submitverify,{'emailer':emailer});
});
});
</script>
The dajax function
#dajaxice_register(method='GET')
def sendEmail(emailer):
logger.warning("type: %s, %s" % (type(emailer),emailer))
email_body = "message"
emailer.addToMessage(email_body)
emailer.send()
message = "Email Sent"
return json.dumps({'message':message})
Here the logger statement returns: type: <type 'unicode'>, <Utils.SIMPL_Emailer instance at 0x103142ab8>. Is there any way to fix this so that I get my emailer object instead of a unicode string?
First try to understand what is happening:
On your template you're trying to save a Python object to a Javascript var:
var emailer = "{{emailer|safe}}";`
But it's not possible. When your template is rendered by Django what you really get is a call to object __str__() method and your Javascript will store the <Utils.SIMPL_Emailer instance at 0x103142ab8> value on your emailer var. And remember: this code run in the client browser. That's why you get an error when you remove the quotes.
To solve it you need to first serialize your emailer object (Turn it into something that could be represented as a String, for example, and then turned back to Python Object). But as pointed by Peter DeGlopper it is a very insecure approach. Never, ever deserialize an whole object that was public accessible. Instead send only the email data to your template. You can create a dictionary with this data, turn it into JSON (it's a serialization too, but this time you are serializating only data) and then pass it to your template.
So do not put your emailer on the template context. Instead create a dictonary and pass it to the template.
Then in your Python sendEmail(emailer) method you'll need to instanciate a new Emailer object and feed it with the data, like:
#dajaxice_register(method='GET')
def sendEmail(email_json):
email = json.loads(email_json) # email_json is a json with your email data only
logger.warning("type: %s, %s" % (type(email_json),email_json))
emailer = Emailer("<with all your params...>")
emailer.addToMessage(email.get('body'))
emailer.send()
message = "Email Sent"
return json.dumps({'message':message})
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
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/