Is it even possible? To call a code-behind c# function from javascript in a visual web part?
It is a complex function so converting all my codes to client side is not an option. I want the logic that is there in this function to happen without a page refresh. This is the background of my issue.
Thanks guys..
You can use jQuery ajax to call server side method and get the response to be used in javascript. This article has simple and good example to show what you need to do.
Code behind
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Javascript
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Why don`t you use a Webservice (Ajax-Enabled WCF Service) which can be called via AJAX?
I think this would be the clean way. Put your logic in an extra class and use this class in the webservice and your webpart. Then you cann call the Method from Code and from Javascript.
Related
I've just started using ASP.NET MVC 4.0 to build a web application. I've been through the tutorials that explain and demonstrate View/Controller/Models, but now I'm wanting to go a step further.
Instead of having all of my pages constantly reload as users interact with my application, i'd like to learn how to make async calls to the server side to load data.
A great example of what I would like to learn how to implement is:
http://demo.aspnetawesome.com/AjaxDropdownDemo/Index
The Drop Downs are bound to each other, and the page never refreshes. Does anyone have some suggestions on where I can go to learn how to begin learning this? Also, since I am using MVC how can I use Model Binding to help make it more simple?
To Make and async calls to your action you can make ajax call as follows
Jquery Code:
var AsyncCall = function () {
$.ajax({
type: "POST",
url: "Home/Index",
data: JSON.stringify(yourData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// Success implementation
},
error: function () {
}
});
};
In Controller :
[HttpPost]
public ActionResult Index(DataType model)
{
// Implementation
return View(model);
}
Recently I learned that you can take a script manager and set the EnablePageMethods="true" this is something I would like to do but is there any security implications ?
Also, Is there a newer better way to this ?
All that EnablePageMethods="true" really does is generate an inline JavaScript proxy that allows for calling back to ASP.NET AJAX Page Methods via the PageMethods syntax.
I prefer using jQuery via its .ajax() method to call ASP.NET AJAX Page Methods, like this:
Code-behind
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
JavaScript:
$.ajax({
type: "POST",
url: "PageName.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Note: Since ASP.NET AJAX Page Methods automatically serialize their response to JSON, then "json" is the return dataType of the AJAX call. contentType describes what you are sending to the server.
It does not have any more security implications than would adding any ordinary web page or service to a website. The needed precautions are the same -- don't use any inputs without validating them first, don't inadvertently return sensitive information in error messages, etc.
There is a newer way, and arguably better, if you don't mind switching to a new platform: ASP.Net MVC, and the related "Web API". (You can use Web API with Webforms also, thanks to Karl Anderson for noting in the comments.)
Is it possible to load and save data to/from a grid using c# code in the back from an aspx page, or does one have to use a web service (or PHP)? I have tried and failed using JSON.Net to map a very simple structure to code a backend structure
Is it possible to use JQuery (an ajax GET I presume) to make a call to a method in the backend code file (.aspx.cs)? I have tried using code from various posts on this forum, but there is little information on the backend code (c#), and all seem to refer to web services. Any help/advice would be much appreciated.
Here is the JavaScript code associated:
var handsontable = $container.data('handsontable');
$(document).find('button[name=load]').click(function () {
$.ajax({
url: "Default.aspx/getJSData",
dataType: 'json',
type: 'GET',
//contentType: "application/json; charset=utf-8",
success: function (res) {
handsontable.loadData(res.data);
$console.text('Data loaded');
},
error: function () {
$console.text('Load error');
}
});
});
You still need to do an Ajax call but you don't need to do a web service (you can). The function you want exposed to the Ajax call put the [WebMethod] Attribute on and an use a Script Manager with the EnablePageMethods attribute set to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
Method to Access:
[WebMethod]
public static void SomeFunction(string message, string name)
{
}
Ajax call using jQuery
(function($) {
$.ajax({
type: "POST",
url: "test.aspx/SomeFunction",
data: "{message:'Hello World', name: 'Bob'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
}
});
});
Reference: Using the WebMethod Attribute
So I have something like this situation:
$(document).on('click', 'a[data-link]', function () {
var $this = $(this);
url = $this.data('link');
$("#imagePreview").load("imageProcess.aspx?" + url);
where url holds GET parameters. But imageProcess.aspx is different than the file I'm in (dashboard.aspx) and I need to reference some panels within my dashboard.aspx file. So my question is, using the .load() function, or even any function that could get the job done, how do I call a function, with GET parameters, in the dashboard.aspx code behind file? I'm fairly new to the .NET framework so I apologize if the question sounds elementary.
In your imageProcess.aspx.cs create a webmethod like:
[WebMethod]
public static string YourMethod(your parameters)
{
//Do Your Work
}
and in your dashboard page, in javascript use jquery to send request your webmethod like:
$.ajax({
type: "POST",
url: "imageProcess.aspx/YourMethod",
data: "{parameter1Name:'" + JSON.stringify(parameter1value) + "', Parameter2Name:'" + JSON.stringify(parmeter2Value) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// do your success work, keep in mind that your returned data will be in data.d
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// do your failuer work
}
});
I hope it will give you a guidance to achieve your task.
Just to make sure: You are trying to access functionality from a different aspx page than the one you are currently on.
I'm not entirely sure if you can do that the easy way by java script. Maybe someone else knows a better way, but the way I would do it is creating ashx service page which will handle your request so you can provide the data you need (in your case an image)
For more information see http://www.dotnetperls.com/ashx
I have an asp.net application with a static page method. I'm using the below codes to call the method and get its returned value.
$.ajax({
type: "POST",
url: "myPage/myMethod",
data: "{'parameter':'paramValue'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {alert(result);}
});
What i got returned is [object Object].
Below is my static method. And I also have EnablePageMethods="true" EnablePartialRendering="true" in my ScriptManager.
[WebMethod]
[ScriptMethod]
public static string myMethod(string parameter)
{
return "Result";
}
Is there a way for me to get the returned value?
Try using Chrome developer tools or the firebug plugin from Firfox. Not sure if IE's developer tools lets you inspect the ajax calls?
The resulting string you are looking for is actually within the result object. You need to look at the d variable. I remember reading somewhere why this was, I think it is ASP.NET playing around :|
Try:
success: function(data) {alert(data.d);}
c#
[WebMethod]
public static string GetTest(string var1)
{
return "Result";
}
Hope this helps.
Its just that you are stuck at the .d that is introduced in the JSON response from ASP.NET 3.5. To quote Dave Ward,
If you aren’t familiar with the “.d”
I’m referring to, it is simply a
security feature that Microsoft added
in ASP.NET 3.5’s version of ASP.NET
AJAX. By encapsulating the JSON
response within a parent object, the
framework helps protect against a
particularly nasty XSS vulnerability.
So just check whether .d exists and then unwrap it. Change your success function like this.
success: function(result) {
var msg = result.hasOwnProperty("d") ? result.d : result;
alert(msg );
}
What about this?
$.ajax({
type: "POST",
url: "myPage/myMethod?paramater=parameter",
success: function(result) {
alert(result);
}
});
I found out the solution.
You can use parseJSON to get the result
http://api.jquery.com/jQuery.parseJSON/
or change the datatype to html to see the actual value.
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
Thank you guys for your help.