I have created Class under App_Code folder there i have created method.
I need to call that class method using JavaScript from Sample.aspx file.
Class:
namespace ContactBook.App_Code
{
//The function need to call...
public class ContactBook_functionalities
{
public static bool MyFunction(string email, string contact)
{
//Code...
}
}
}
JavaScript:
<script type="text/javascript">
function callMyFunc(email, contact)
{
//var x = MyFunction(string email, string contact);
}
</script>
[WebMethod] is not working for Class functions.
I don't thing you can do that because:
ASPX is server side, whereas JavaScript is client side
some components from a ASP site are compiled
What you can do is expose a route (if you were using MVC desing pattern) on the server that calls that function (or an Api for that mather).
You need to expose an HTTP handler in ASP.net or Controllers / Web API in MVC for your JavaScript to have the capability of talking to the server. Simple classes are not accessible outside ASP.net Application via JavaScript.
After creating your own controller/HTTP handler, you need to send an AJAX request to the controller and it should look like this code below:
$.ajax({
url: "sampleurlhere",
type: "POST"//POST or GET,
data: {
id: "sample id as parameter"
},
success: function(e) {
//this event fires up when response arrives.
}
})
Related
How can i call javascript in a blazor server application? I am trying to follow this document
http://www.binaryintellect.net/articles/aede436b-4c57-4551-a7b4-a005f2aed499.aspx
On my ui.razor file i created the following code
#inject IJSRuntime JsRuntime;
...
private async void callWidgetApplication()
{
var fetched = await JSRuntime.InvokeAsync<bool>("fetchComponenent", DotNetObjectReference.Create(this));
}
I create a file on my wwwroot call Widget.js. this is what i have for the moment
function fetchComponenent() {
return true;
}
But i keep getting an error on my invokeasync.
CS1503 Argument 2: cannot convert from 'Microsoft.JSInterop.DotNetObjectReference<InfoAccessBlz.Pages.InfoAccess>' to 'object?[]?'
The whole reason in using javascript is to call an other website using ajax. So maybe if there is a better way, this is not an api, but its to retrieve an html site.
await JsRuntime.InvokeVoidAsync("fetchComponenent");
Your JavaScript Function doesn't accept any parameter and add the JavaScript file to the _Host.cshtml like this
<script src="~/Widget.js"></script>
I have a simple web application that operates with a set of words using JS. In order to test the main code I just put a needed data in a variable in my script.
CONST WORDS = [
["Computer", "Ordinateur", "https://www.lifewire.com/thmb/nNDKywb8qvKzhxelVAR95sEHBj0=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/Acer-aspire-x3300-5804ec185f9b5805c2b6b9e6.jpg"],
["Function", "Fonction", "http://latex-cookbook.net/media/cookbook/examples/PNG/function-plot.png"],
["Server", "Serveur", "https://effortz.com/wp-content/uploads/dedicated-hosting-server.png"]
]
Now I need to build a database (already done) and get such data from the server. So, the question is how do I acquire JSON file from the server using JS? I know how to make GET requests, but what should I do on the server to make it response? (or may be there is an easier way to get this data in JS, considering that I already got it from DB and can easy display on the webpage).
Here is a backend code
namespace LFrench
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Words> WordsSet = Words.GetWords("Business");//recieving from DB a set of words, that i need to use in JS
}
}
}
The thing you need to understand is the flow of your request. if you strictly want to do it in the Page_Loag event then I suppose you will have to make a method in your Javascript that will actually accept your data as parameter and then call the Javascript method from the C# CodeBehind Assuming that the data in the parameter is in JSON format. This method works but is not very efficient.
Other way is, in your JQuery side, you should make an ajax call to a WebMethod of yours in the CodeBehind that will actually send the response in JSON format. This is cleaner way of doing it.
Your JQuery should look like:
$(document).ready(function(){
$.ajax({
method: "GET", accept: "application/json; charset=utf-8;",
url: 'MyPage.aspx/GetDataFromDB', success: function(data){
console.log('Success Response in JSON: ' + data.d); // notice *data.d*, Calling from WebMethods returns the object encoded in the .d property of the object.
}, fail: function(err){
console.log(err);
}
});
});
And your CodeBehind should look like:
[WebMethod]
public static string GetDataFromDB()
{
var myData = YourDbCall(); // Some method to retrieve data from database
var body = new
{
Firstname = myData.Firstname,
Lastname = myData.Lastname,
Email = myData.Email,
// Any Other Information
};
var json = JsonConvert.SerializeObject(body);
return json;
}
EDIT
Here is how your Word Set will be sent back as JSON:
[WebMethod]
public static string GetDataFromDB()
{
List<Words> WordsSet = Words.GetWords("Business");
return JsonConvert.SerializeObject(WordsSet);
}
Make sure you have installed Newtonsoft.JSON from Nuget Package Manager Console. if not you can Open Package Manager Console and run this command:
PM> Install-Package Newtonsoft.Json
You need to make json return type method on serverside. Than call it from your get method and do your method on serverside and fill the List and return that list by converting JSON format.
I am currently using jquery to send data from javascript to a php file to execute some server side code:
$.ajax({
url: 'myfile.php', //instead of php, can I call a exe (c#) or asp page here?
type: "POST",
data: ({name: Dummy}),
success: function(data){
}
});
I am facing issues in passing values from my javascript to php file, data is dropped at adfs (eso). So I want to know if a c# exe, or an asp page can be called instead of a php and is it advisable, are there any other way of passing values from client end to server side, my website is made of html files and javascript only.
tried passing this aspx page as URL in above code
Url ="mydomain.com/site/default.aspx";
on the aspx page I am reading
string[] keys = Request.Form.AllKeys;
but the aspx page isnt getting executed (like a php does otherwise)
Take a look at this link, ASP.Net have something know as WebAPI which is great for HTTP services and potentially perfect for what you want.
EDIT:
Based on a comment here is a really basic controller with Get and Post verbs
public class DummiesController : ApiController
{
[HttpGet()]
[Route("api/dummies")]
public IHttpActionResult Get()
{
return this.Ok(new[] {new Dummy(), new Dummy()});
}
[HttpGet()]
[Route("api/dummies/{id}")]
public IHttpActionResult GetById(int id)
{
return this.Ok(new Dummy());
}
[HttpPost]
[Route("api/dummies")]
public IHttpActionResult Post(Dummy dummy)
{
int id = 1;
return this.Created($"api/dummies/{id}", dummy);
}
}
I have an MVC application which i am trying to give the user the opportunity to download a zip of files,but unsuccesfully.Let me explain further.
Inside my view(ImageViewer.cshtml) i have a div class with an on click event that when pressed i call the controller method(ImageViewerController.GetZipPhotos) which handles the download of the zip file.See below:
div class="text" onclick="GetZipPhotos()">Download</div>
and the Javascript that get called is this:
function GetZipPhotos() {
$.ajax({
url: '#Url.Action("GetZipPhotos", "ImageViewer",Request.Url.Scheme)',
type: 'POST',
contentType: 'application/zip',
error: function () {
alert('There was an error!'+result);
}
});
}
Now, inside my ImageViewerController i have the following method:
[HttpPost]
public ActionResult GetZipPhotos()
{
ZipResult newZipResult=new ZipResult(
Server.MapPath("~/File1.txt"),
Server.MapPath("~/File2.txt")
);
newZipResult.OutPutZipFileName = "PhotosZip.zip";
return newZipResult;
}
and the declaration of the ZipResult custom action is:
public class ZipResult:ActionResult
{
private IEnumerable<string> _filesToZip;
private string _outPutZipFileName="ZipFile.zip";
public ZipResult(params string[] filesToZip)
{
this._filesToZip = filesToZip;
}
public override void ExecuteResult(ControllerContext context)
{
using (ZipFile oneZipFile = new ZipFile()) {
oneZipFile.AddFiles(_filesToZip);
context.HttpContext.Response.ContentType = "application/zip";
context.HttpContext.Response.AppendHeader("content-disposition", "attachment; filename=" + _outPutZipFileName);
oneZipFile.Save(context.HttpContext.Response.OutputStream);
}
}
}
The problem is that the code ofcourse doesn't work because the name of the view that called the controller is different from the actual method(GetZipPhotos).The view's name is ImageViewer.cshtml and the controller's name is ImageViewerController.
As fas as i have understood, the MVC framework uses code conventions, so it expects the name of the method to be the same as the view.The problem is that my view and the method are diferrent so the response never gets to back to the view.
I thought of creating a new view that has basically nothing inside, just to call it from the method and return the zip file.If this could be a possible solution, how can i tell from the action result which view to send the response?
No need to use ajax for the file download. The browser will normally start the download and keep you on the same page. Also, no need for a custom action result, you can just use FileResult. Try something like this:
public FileResult GetZipPhotos()
{
var filesToZip = new List<string> { Server.MapPath("~/File1.txt"), Server.MapPath("~/File2.txt") };
var oneZipFile = new ZipFile();
oneZipFile.AddFiles(filesToZip);
return File(oneZipFile.ToByteArray(), "application/zip", "PhotosZip.zip");
}
Of course, you'll need to figure out this part oneZipFile.ToByteArray(), but the ZipFile class probably already has something like that.
Your ajax call is redirecting the response into nowhere.
I would do it like this:
use a hidden iframe, change its src to the desired path in your function and it should be prompting a file dialog.
I have an asp.net application, one page is using JQuery.Ajax to call a WebMethod function in aspx code
// Default.aspx.cs
[WebMethod]
public static string GetCustomersCount()
{
...
dbReader.OnReadAsyncComplete += (_o, _e) => { ... };
...
}
this function reads data from database (asynchronously) and has an event handler OnReadAsyncComplete.
Now how can I access any client or server UI element (label, textbox - whatever) - to write some value in that UI element?
WebMethod is static, so neither Response object nor UI Elements with runat="server" are not accessible in dbReader.OnReadAsyncComplete
If you want to do things that way, that's what postback-style code is for. If you're doing AJAX-style programming instead, your client-side code is where you update your page:
$.ajax(...).then(function(data) {
$('#your-label').text(data.someValue);
});